0

I have two mongodb model as following.

const CompanySchema = new Schema(
  {   
    sections: [{
      name: { type: String },
      budgets: [{ // indicates from CalcSchema
        index: { type: Number },
        title: { type: String },
        values: [Number],
        sum: { type: Number, default: 0 },
      }],
    }]
  },
  { timestamps: true }
);

const CalcSchema = new Schema({
    budget: {
        type: Schema.Types.ObjectId, // I want to populate this field. this indicates budget document in Company model
        ref: "Company.sections.budgets" //it's possible in mongoose?
    },
    expense: {
        type: Number,
        default: 0
    }
});

budget field indicate one of budgets field in CompanySchema. So I want to populate when get Calc data. But I don't how to populate embedded document.

I tried set ref value to ref: "Company.sections.budgets". but it's not working.

Please anyone help.

Daniel.Wang
  • 2,242
  • 2
  • 9
  • 27
  • please read this link, I know it will be useful for you and solve another populate issues: https://dev.to/paras594/how-to-use-populate-in-mongoose-node-js-mo0 – mohammad javad ahmadi Jan 20 '21 at 07:33
  • Does this answer your question? [How to populate nested entities in mongoose?](https://stackoverflow.com/questions/36996384/how-to-populate-nested-entities-in-mongoose) – mohammad javad ahmadi Jan 20 '21 at 07:36
  • @mohammadjavadahmadi thanks for your comment. But it's not helpful for my case. i want to populate subdocument of other schema. the case of your answer is populate other schema from subdocument in one schema. it's different case. – Daniel.Wang Jan 20 '21 at 07:42

1 Answers1

0

Finally, I found answer myself.

There is useful plugin for it.

https://github.com/QuantumGlitch/mongoose-sub-references-populate#readme

And I learned that my schema structure was wrong. It's anti-pattern in mongodb.

Daniel.Wang
  • 2,242
  • 2
  • 9
  • 27
  • Why is it and anti-patttern? I am having the same issue and not sure if I should change my schema or usethe plugin. – Nicolas Dec 22 '22 at 15:37