The undefined property of MikroORM is not being returned

After experimenting with MikroORM, I've encountered a situation that has left me perplexed.

Here is the snippet of code in question:

    const user = await appCtx.em.findOne(User, {email, accessToken})
    if (!user) {
        return
    }

    console.log('!* user before', user);
    user.accessToken = undefined
    console.log('!* user after', user);

This code produces the following output in the console:

!* user before User {
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5061623132636236637d313669647d643536617d693369657d336564646531666336356768103120397d243523247e333f3d">[email protected]</a>',
  name: 'Username',
  verifyToken: null,
  verifyTokenCreatedAt: null,
  verifiedAt: 2024-10-24T06:07:22.417Z,
  accessToken: '80b1b652-2f45-43db-8200-b9d003ad1ddb',
  createdAt: 2024-10-24T06:07:22.400Z,
  updatedAt: 2024-10-24T06:07:22.417Z,
  id: '3eab5128-5549-401d-88f6-98c2ff9f517c'
}
!* user after User {
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8e9eab9baebeabeebf5b9bee1ecf5ecbdbee9f5e1bbe1edf5bbedececedb9eeebbebdefe098b9a8b1f5acbdabacf6bbb7b5">[email protected]</a>',
  name: 'Username',
  verifyToken: null,
  verifyTokenCreatedAt: null,
  verifiedAt: 2024-10-24T06:07:22.417Z,
  createdAt: 2024-10-24T06:07:22.400Z,
  updatedAt: 2024-10-24T06:07:22.417Z,
  id: '3eab5128-5549-401d-88f6-98c2ff9f517c'
}

The issue at hand is my confusion over why the accessToken property is missing from the 'user after' log. I expect to see this property returned with a value of null in my tests. What am I overlooking?

To provide a comprehensive overview, here is my Entity definition:

@Entity()
export class User {
    [OptionalProps]?: 'createdAt' | 'updatedAt'

    @PrimaryKey({type: "string"})
    id = crypto.randomUUID()

    @Property({type: "string", unique: true})
    email: string

    @Property({type: "string"})
    name: string

    @Property({type: "string", nullable: true})
    verifyToken?: string

    @Property({type: "Date", nullable: true})
    verifyTokenCreatedAt?: Date

    @Property({type: "Date", nullable: true})
    verifiedAt?: Date

    @Property({type: "String", nullable: true, index: true})
    accessToken?: string

    @Property({type: "Date"})
    createdAt = new Date();

    @Property({type: "Date", onUpdate: () => new Date() })
    updatedAt = new Date();

    constructor({email, name}: User) {
        this.email = email
        this.name = name
    }
}

And here is how I initialize it:

export const orm = await MikroORM.init({
    entities: [User],

    dbName: mikroConfig.dbName,
    host: mikroConfig.host,
    user: mikroConfig.user,
    password: mikroConfig.password,

    logger: (message: string) => console.debug(message), // defaults to `console.log()`
})

Answer №1

The ORM does not automatically change undefined to null, and when logging the entity, any undefined values are left out. Although technically the value exists, it will be excluded when serializing the entity, making it unnecessary to display it when using console.log.

If you specifically want to see and include it in the serialized form or JSON, you can use explicit null. This requires adjusting the entity definition to allow for the presence of a null value. Keep in mind that this adjustment may cause reflect-metadata to stop functioning if union types cannot be inferred, but since you already provide the type option explicitly, this should not be an issue.

// entity def
accessToken?: string | null

// usage
user.accessToken = null

You have the choice whether to maintain optionality at the type level; accessToken: string | null will also work effectively.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The 'mat-button' component from Angular Material 2 is displaying as a standard button

Here is my app.component.ts: import { Component } from '@angular/core'; import {MatButtonModule} from '@angular/material/button'; @Component({ selector: 'app-root', templateUrl: './app.component.html', style ...

Tips for addressing style issues within innerText

I am trying to use PrismJS to highlight HTML code, but the inner text function doesn't recognize line breaks (\n). <pre class="language-markup background-code"><code [innerText]="getHtmlCode()""></code> I have been working wi ...

Retrieve the value of one of the two variables that undergo a change in value

In my current project, I am dealing with a function that takes in two variables. These variables are subject to change at any point during the execution of the program. My requirement is to identify which variable has changed so that further operations can ...

Is it possible to retrieve the selected DataList object in Angular 10?

I encountered an issue while creating an Input field with DataList. My goal was to retrieve the entire object associated with the selected option, but I could only access the selected value. Previous suggestions mentioned that DataList items should be uniq ...

Guide to pairing array elements in JavaScript

To streamline the array, only elements with a value equal to or greater than the set threshold will be retained. These selected elements will then be used to create a new array comprising multiple objects. Each object will consist of two properties: the st ...

At what point are routed components initialized?

Here is a route setup I am working with: path: ':id', component: ViewBookPageComponent }, After adding this route, an error keeps popping up: Error: Cannot read property 'id' of null I haven't included a null check in the compo ...

Key ConfusionUpdated descriptionKeyword confusion

What is the reason for the absence of errors in this code snippet: interface X { a: string; b?: string; } type Y<T> = { [key in keyof T]: boolean; } class A<Definition> { constructor(public readonly definition: Definition, publ ...

Transform Text into Numeric Value/Date or Null if Text is Invalid

Consider the TypeScript interface below: export interface Model { numberValue: number; dateValue: Date; } I have initialized instances of this interface by setting the properties to empty strings: let model1: Model = { numberValue: +'', ...

Connect the HTML link component tag to a component that is passed through the constructor

I have recently started learning about Angular and TypeScript. Within my AppComponent HTML file, I include another component using the code <app-listpost></app-listpost> In the TypeScript file, I import the ListPostComponent into my AppCompon ...

What is the best way to dynamically add data to a JSON file?

image of JSON file Just a heads up: I'm looking to add data directly without the need to write it to a .json file, perhaps by using Angularfire2 database. user = { name: 'Arthur', age: 21 }; const options = {Headers, responseType: &apo ...

Unable to utilize the useState hook in TypeScript (Error: 'useState' is not recognized)

Can you identify the issue with the following code? I am receiving a warning from TypeScript when using useState import * as React, { useState } from 'react' const useForm = (callback: any | undefined) => { const [inputs, setInputs] = useS ...

Tips for accessing the value from a subscription within a function in Ionic 3

I am working on a function that retrieves a JSON file from a specific URL. The issue I am facing is that I am trying to access a random object from this data within the file, stored in this.data. However, when I attempt to console.log(this.data) outside of ...

Creating or deleting multiple batches of entries in Firebase Realtime Database

I am currently utilizing Firebase real time database in the following way: createSoldLead(soldLead: SoldLeadModel): void { const soldLeadsReference = this.angularFireDatabase.list<SoldLeadModel>( `groups/${this.groupId}/soldLeads` ); ...

Trouble encountered when implementing multiple conditions for checkboxes in an Angular 8 application

In my form, there are four checkboxes (3 for options and 1 for setting a plan) which have specific requirements: If all three options are checked, the set plan checkbox is automatically checked and the options disappear If the set plan checkbox is checke ...

Open new tab for Angular OAuth2 OIDC login process

Currently, I am incorporating the authorization code flow using angular-oauth2-oidc in my Angular application. It is a fairly straightforward process. However, I would like to have the ability for the login flow to open in a new tab when the login button ...

Concatenate all sub-items within a JSON object

I have 2 Objects like this : [ { _id: ObjectId("62990f96345ef9001d9f2dfe"), deletedAt: null, expiredAt: ISODate("2022-06-05T19:29:26.746Z"), dataBarang: [ { vendor: ObjectId("6215dd91139c99003fe4c7cd ...

Setting a callback function as a prop for react-paginate in TypeScript: A step-by-step guide

When using react-paginate, there is a prop called onPageChange with the following type: onPageChange?(selectedItem: { selected: number }): void; After implementing it like this: const onPageChange = (selected): void => { console.log(selected); } ...

Is there a more efficient method for invoking `emit` in Vue's Composition API from an external file?

Is there a more efficient way to access the emit function in a separate logic file? This is my current approach that is functioning well: foo.js export default (emit) => { const foo = () => { emit('bar') }; return { foo }; } When ...

The data type 'string' cannot be assigned to the data type 'Position'

Currently, I am in the process of converting React js to typescript. The component being used is a Class Component. I would like to obtain CSS settings through props and apply them to an element. How can I resolve this issue? render(){return( <span st ...

Invoke index functions within a component

I have a widget/component written in Angular 4 within the index.html file. Before and after this angular app, there are various HTML elements due to the nature of it being an additional component for the website. The head section of the index file include ...