Search code examples
mikro-orm

Correct use of IdentifiedReference and { wrappedReference: true }


With this I don't end of understand it and I don't want pollute the original issue. need I use always { wrappedReference: true } with IdentifiedReference?

Because, this fail:

@Entity({ collection: "account" })
export class AccountEntity implements IdEntity<AccountEntity> {
    @PrimaryKey()
    public id!: number;

    @OneToOne(() => ArtistEntity, "account", { wrappedReference: true })
    public artist!: IdentifiedReference<ArtistEntity>;
}

@Entity({ collection: "artist" })
export class ArtistEntity implements IdEntity<ArtistEntity> {
    @PrimaryKey()
    public id!: number;

    @OneToOne(() => AccountEntity, { wrappedReference: true })
    public account!: IdentifiedReference<AccountEntity>;
}

with:

src/entities/artistEntity.ts(15,38): error TS2345: Argument of type '{ wrappedReference: boolean; }' is not assignable to parameter of type '"id" | "name" | "password" | "email" | "image" | "artist" | "collections" | "studios" | ((e: AccountEntity) => any) | undefined'. Object literal may only specify known properties, and 'wrappedReference' does not exist in type '(e: AccountEntity) => any'.

So, this would the correct?

@Entity({ collection: "account" })
export class AccountEntity implements IdEntity<AccountEntity> {
    @PrimaryKey()
    public id!: number;

    @OneToOne(() => ArtistEntity, "account", { wrappedReference: true })
    public artist!: IdentifiedReference<ArtistEntity>;
}

@Entity({ collection: "artist" })
export class ArtistEntity implements IdEntity<ArtistEntity> {
    @PrimaryKey()
    public id!: number;

    @OneToOne(() => AccountEntity)
    public account!: IdentifiedReference<AccountEntity>;
}

Solution

  • The problem is that you are trying to use second parameter of @OneToOne decorator for options object, but that is currently supported only for first or third parameter

    // works if you use the default `TsMorphMetadataProvider`
    @OneToOne()
    public account!: IdentifiedReference<AccountEntity>;
    
    // use first param as options
    @OneToOne({ entity: () => AccountEntity, wrappedReference: true })
    public account!: IdentifiedReference<AccountEntity>;
    
    // use third param as options
    @OneToOne(() => AccountEntity, undefined, { wrappedReference: true })
    public account!: IdentifiedReference<AccountEntity>;
    
    // you can also do this if you like
    @OneToOne(() => AccountEntity, 'artist', { owner: true, wrappedReference: true })
    public account!: IdentifiedReference<AccountEntity>;
    

    But this will change before the final v3 release, so if you will use the TsMorphMetadataProvider (default one), it will always work even without the explicit wrappedReference: true.

    Here is an issue you can subscribe to regarding this upcoming change: https://github.com/mikro-orm/mikro-orm/issues/265

    (it is about nullability, but this be another side effect of this change)