MikroORM referenced entity JSON value

78 views Asked by At

I don't know if this is a bug or correct behavior, but when I return json from an entity that has a reference Ref to @ManyToOne entity I get "city": "bd612c71" for that reference, but I thought it was supposed to return { "city": { "id": "bd612c71" } }

{
  "id": "80856ca0",
  "createdAt": "2023-07-10T01:48:48.000Z",
  "updatedAt": "2023-07-10T01:48:48.000Z",
  "hospital": {
    "id": "d8f6f9ce",
    "city": "bd612c71",
    "country": {
      "id": "cfb0a1c6",
      "createdAt": "2023-07-10T01:48:48.000Z",
      "updatedAt": "2023-07-10T01:48:48.000Z"
    },
    "deletedAt": null
  }
}

This is the Hospital entity

@Entity({
    tableName: 'hospital'
})
export default class Hospital extends AggregateRoot<Hospital, 'id'> {

    @PrimaryKey({ autoincrement: false, unique: true, type: 'varchar', length: 8, nullable: false })
    id!: string

    @ManyToOne(() => City, { ref: true })
    city!: Ref<City>

    @ManyToOne(() => Country, { ref: true })
    country!: Ref<Country>

    // More properties here
}

And this is the City Entity

 @Entity({
        tableName: 'city'
    })
    export default class City extends AggregateRoot<City, 'id'> {

        @PrimaryKey({ autoincrement: false, unique: true, type: 'varchar', length: 8, nullable: false })
        id!: string

        @Property({ unique: true, type: 'character', length: 100, nullable: false })
        name!: string

        @OneToMany(() => Hospital, hospital => hospital.city)
        hospitals = new Collection<Hospital>(this)
    }

AggregateRoot is my own custom class that extends BaseEntity<T, PK>

How can I make it return { "city": { "id": "bd612c71" } } ?

1

There are 1 answers

0
Martin Adámek On BEST ANSWER

This is expected behavior, unloaded references are serialized as FKs, not objects.

In v6, you can force the behavior you want via serialization: { forceObject: true } in your ORM config.

It's not documented for the implicit serialization, but this flag has been ported there too recently.

https://mikro-orm.io/docs/next/serializing#implicit-serialization

In v5 you'd have to use explicit serialization (which has this flag already), or custom property serializer.