用猫鼬填充子文档数组字段

时间:2020-07-31 11:34:00

标签: node.js mongodb mongoose mongoose-populate

我知道之前曾有人问过这个问题,但是经过数小时的研究,我尝试了几种方法来解决我的问题而没有成功。

架构

def GregorianIsLeapYear(y):
    if ((y % 4) != 0)
        return False
    if ((y % 100) != 0)
        return True
    return (y % 400) == 0

我要做什么

我试图在 const ValuationsSchema = new Schema( { value: { type: Number, required: true, min: 0, max: 5 }, author: { type: Schema.Types.ObjectId, refPath: "fromModel", required: true, }, fromModel: { type: String, required: true, enum: ["usertype1", "usertype2", "usertype3"], trim: true, }, }, { timestamps: true, } ); const UserSchema = new Schema( { name: { type: String, required: true, trim: true }, valuations: [ValuationsSchema], }, { timestamps: true, } ); 的{​​{1}}数组中填充author的{​​{1}}字段。

样本数据

预期结果

ValuationsSchema

获得结果

valuations

已经尝试过的解决方案

此刻,我手动填充了该字段,但这是一个好习惯,因此,我尝试在可能的情况下使用该API。

就我而言,执行此操作应该可以完成这项工作,但事实并非如此。

user

也没有运气尝试过这个

{
  _id: 5f1ef9f6039fea10c437939c,
  name: 'Jose Maria',
  createdAt: 2020-07-27T15:59:50.529Z,
  updatedAt: 2020-08-01T15:34:47.414Z,
  valuations: [
    {
      _id: 5f258b973c0ac544869c0434,
      value: 5,
      author: Object,
      fromModel: 'particular',
      createdAt: 2020-08-01T15:34:47.414Z,
      updatedAt: 2020-08-01T15:34:47.414Z
    }
  ]
}

也尝试过deepPopulate package,但结果相同。

1 个答案:

答案 0 :(得分:1)

refPath应该来自父级valuations.fromModel

  • 在架构中更改它,
author: {
    type: Schema.Types.ObjectId,
    refPath: "valuations.fromModel",
    required: true,
}
  • 单文档明智的人口
let user = await User.find();
let user1 = await user[0].populate("valuations.author").execPopulate();
  • 所有文档数量
let users = await User.find().populate("valuations.author").execPopulate();

注意:猫鼬版本5.2.9中有一个错误#6913refPath在嵌套数组中不起作用,请确保已安装最新版本。