Search code examples
javascriptnode.jspostgresqlormmikro-orm

Mikro-ORM: How can I return first item in collection?


I have 2 entities like the ones below, but I only ever want to return a single stats object. Mikro-ORM returns this as an array.

Is there a way to tell Mikro-ORM to return the first element in an array as an object?

The end result being something like deck.stats.stats_property. Instead of deck.stats[0].stats_property.

@Entity()
export class Deck extends MyBaseEntity<Deck> {
  @OneToMany({ entity: () => DeckStats, mappedBy: (stat) => stat.deck })
  stats = new Collection<DeckStats>(this);

  constructor( ...extraValues }: DeckConstructorValues) {
    super(extraValues);
  }

@Entity()
export class DeckStats extends BaseEntity< DeckStats > {
  @ManyToOne(() => Deck, { wrappedReference: true, primary: true, mapToPk: true })
  deck: string;

  @ManyToOne(() => User, { wrappedReference: true, primary: true, mapToPk: true })
  user: string;

  [PrimaryKeyType]?: [User, Deck];
    
  constructor({ deck, user }: DeckStatsConstructorValues) {
    super();
    this.deck = deck.id;
    this.user = user.id;
  }

Solution

  • You can either implement custom toJSON method on the entity, which gives you more control, or here it should be enough to just use property serializer:

    https://mikro-orm.io/docs/serializing#property-serializers

    @OneToMany({
      entity: () => DeckStats,
      mappedBy: (stat) => stat.deck,
      serializer: value => value[0], // <-- this is the new line
    })
    stats = new Collection<DeckStats>(this);
    

    This will have effect only for the serialized form of the entity, so not when you do console.log(e), but only after console.log(JSON.strigify(e)).