How to load embedded reference schema in nestjs mongodb?

1.4k views Asked by At

Currently I am working on API using nestjs. It has the code like below.

@ObjectType()
@Schema()
@InputType('BuyInput', { isAbstract: true })
export class Buy extends CoreEntity {
  @Prop(raw([BuyItemType]))
  @Field(() => [BuyItemType])
  items: BuyItemType[];

  @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' })
  user: User;

  @Prop({
    type: String,
    enum: BuyStatus,
  })
  @Field(() => BuyStatus)
  @IsEnum(BuyStatus)
  status: BuyStatus;

  @Field()
  @Prop({ name: 'deliveryCharge' })
  deliveryCharge: number;

  @Field()
  @Prop({ name: 'finalCharge' })
  finalCharge: number;
}

which has user as reference schema. Right now I have to use populate to get user while querying Buy schema. like this.

buyModel.find().populate('user');

Could I automatically load without using populate?

1

There are 1 answers

0
Alex Dumitru On

You can use mongoose-autopopulate plugin, or the post hook, as is described in the mongoose official documentation.