skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    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 });
    

  2. @prop({
      ref: () => QueryRule | ChildRule,
      required: true
    })
    rules: Ref<QueryRule | ChildRule>[];
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search