【问题标题】:Mongoose Multiple Level Populate with RefpathMongoose 使用 Refpath 进行多级填充
【发布时间】:2021-10-11 09:14:18
【问题描述】:

我正在尝试使用带有嵌套路径但带有引用路径的 Mongoose populate() 功能:

子架构:

let child = new Schema({
  item: {
    type: Schema.Types.ObjectId,
    required: true,
    refPath: "itemType",
  },
  itemType: {
    type: String,
    required: true,
    enum: ["typeA", "typeB"],
  },
});

父架构:

let parent = new Schema({
  children: [child],
});

构建模型后,我运行查询:

let mQuery1 = Parent.find().populate({
  /* Type 1, does not populate at all. */ path: "children",
  populate: { path: "item" },
});

这什么都不做。

let mQuery2 = Parent.find().populate({
  path: "children",
  populate: [
    { path: "item", model: "typeA" },
    { path: "item", model: "typeB" },
  ],
});

此查询最终会填充一种类型的字段,而其他类型则不填充(例如,填充 typeA 并为 typeB(s) 返回 null)。

所以我的问题是,如何填充使用 refPath 的嵌套字段?

干杯。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-populate


    【解决方案1】:

    我找到了答案,我想我会分享

    您不需要像这样填充模型:

    <br>
    let mQuery2 = Parent.find().populate({<br>
      path: "children",<br>
      populate: [<br>
        { path: "item", model: "typeA" },<br>
        { path: "item", model: "typeB" },<br>
      ],<br>
    });<br>
    

    只是:

    <br>
    let mQuery2 = Parent.find().populate({ <br>
      path: "children", populate: <br>
        {path: "item"}<br>
    })<br>
    

    但是,在您的发布路线中,您必须有 itemType,其值为 typeA 或 typeB。然后将自动填充相应的模型。我还设法仅在后端自动将所选模型传递给 itemType,因此无需手动输入模型名称。

    这是帮助我解决此问题的链接: https://github.com/Automattic/mongoose/issues/7273

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-08
      • 2020-12-22
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 2018-07-19
      • 2015-08-07
      • 1970-01-01
      相关资源
      最近更新 更多