Mongodb Populate is not populating document in Node.js

Issue

I am using typegoose and my Query and QueryRule models are as below.

export class Query {
  @prop()
  queryRule: Ref<QueryRule>;
}
export class QueryRule {
  @prop()
  condition: Condition;

  @prop()
  rules: Ref<QueryRule | ChildRule>[];
}

I am using the following query to populate.

await QueryModel.findById(queryId).populate('queryRule');

My Query Document is as below.

{"_id":{"$oid":"6283d73baffa60c38af8c2f0"},"name":"test","queryRule":{"$oid":"6287c8f0e3ab4b5dd7238ef3"}}

My QueryRule Document is as below.

{"_id":{"$oid":"6287c8f0e3ab4b5dd7238ef3"},"condition":1,"rules":[],"__v":0}

But when I access condition and rules of QueryRule using populate query. I am getting undefined even though values exist in that document.

What am I doing wrong here?

Solution

I needed 2 things for this.

  1. First is I was missing { ref: () => QueryRule }
  2. Then in populate I had to pass model like this { path : 'queryRule', model: QueryRuleModel }
export class Query {
  @prop({ ref: () => QueryRule })
  queryRule: Ref<QueryRule>;
}
let query: Query = await QueryModel
      .findById(queryId)
      .populate({ path : 'queryRule', model: QueryRuleModel });

Answered By – Anonymous Creator

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.