Home > Back-end >  Mongoose RefPath, running populate() with NestJS
Mongoose RefPath, running populate() with NestJS

Time:02-26

I registered by Schema with mongoose using Dynamic ref. I followed the documentation as seen here: https://mongoosejs.com/docs/populate.html#dynamic-ref

@Schema({ collection: 'quotations' })
export class QuotationEntity {
  
  @Prop({ 
    required: true,
    enum: {
      values: ['PersonalClientEntity', 'CommercialClientEntity'],
      message: 'Please supply a valid client type.  Allowed: \'PersonalClientEntity\' or \'CommercialClientEntity\'.'
    },
    type: String
  })
  clientType: String;

  @Prop({ type: MongooseSchema.Types.ObjectId, refPath: 'ClientType', required: true })
  clientRef: Types.ObjectId;
}

So I save an ObjectId under the clientRef field which needs to reference the clientType field. So when I use the populate() method, it needs to either populate 'PersonalClientEntity' or 'CommercialClientEntity'.

So I run the following query:

await this._model.find({ companyRef: companyId }).populate('clientRef').exec();

This does not populate anything. When I replace the ref inside my Schema and pass in the actual correct reference, like so:

@Prop({ type: MongooseSchema.Types.ObjectId, ref: 'PersonalClientEntity', required: true })
  clientRef: Types.ObjectId;

then the populate() method works perfectly. Am I doing something wrong within my Schema with the refPath, or am I missing something else?

CodePudding user response:

Okay, so after going away from the issue, and coming back, I saw my mistake. The numb nut that I am, made a spelling error.

This is my refPath:

refPath: 'ClientType'

and this is my model:

clientType: String;

See the issue? See the issue? Yeah, So I wanted to kick myself.

  • Related