使用 Mongoose 填充子文档数组字段

Populate subdocument array field with Mongoose

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

架构

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

我想做什么

我正在尝试在 uservaluations 数组中填充 ValuationsSchemaauthor 字段。

示例数据

预期结果

{
  _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
    }
  ]
}

得到结果

{
  _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: 5f1edaa83ce7cf44a2bd8a9a,
      fromModel: 'particular',
      createdAt: 2020-08-01T15:34:47.414Z,
      updatedAt: 2020-08-01T15:34:47.414Z
    }
  ]
}

已经尝试过的解决方案

目前我手动填充了该字段,但由于这是一个很好的做法,我正在尝试尽可能使用 API。

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

    await user.populate("valuations.author").execPopulate();

也尝试过这个但没有成功:

    await user.populate({
                        path: "valuations",
                        populate: {
                          path: "author",
                        },
                      }).execPopulate();

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

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

Note: There is a bug #6913 in mongoose version 5.2.9, refPath not working in nested arrays, Make sure you have installed latest version.