Home > database >  Mongodb Populate is not populating document in Node.js
Mongodb Populate is not populating document in Node.js

Time:05-24

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?

CodePudding user response:

@prop({
  ref: () => QueryRule | ChildRule,
  required: true
})
rules: Ref<QueryRule | ChildRule>[];

CodePudding user response:

Your issue seems to be that you are missing the required option ref, see Reference other Classes from the Typegoose Documentation.

In your case your code should look more like:

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

export class QueryRule {
  @prop()
  condition: Condition;

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

As for Ref<QueryRule | ChildRule>[], you will either have to limit it to one on the 2 possibilities or use discriminators, see Non-Nested Discriminators from the Typegoose Documentation.

Also as a small side-note, if your condition: Condition is not also a typegoose class, it will become Mixed, which is basically a any type at runtime in mongoose.

  • Related