【问题标题】:How to populate sub document of another model in mongoose?如何在猫鼬中填充另一个模型的子文档?
【发布时间】:2021-04-24 12:45:01
【问题描述】:

我有两个 mongodb 模型如下。

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 字段表示 CompanySchema 中的预算字段之一。 所以我想在获取 Calc 数据时进行填充。 但我不知道如何填充嵌入文档。

我尝试将参考值设置为ref: "Company.sections.budgets"。但它不起作用。

请任何人帮忙。

【问题讨论】:

标签: node.js mongodb mongoose mongoose-populate


【解决方案1】:

终于,我自己找到了答案。

有一个有用的插件。

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

我了解到我的模式结构是错误的。这是 mongodb 中的反模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 2020-04-29
    • 2016-05-16
    • 2020-04-30
    • 2017-05-07
    • 2021-02-11
    • 2021-06-29
    • 2016-08-17
    相关资源
    最近更新 更多