Node.js 用Mongoose填充子文档数组字段

Node.js 用Mongoose填充子文档数组字段,node.js,mongodb,mongoose,mongoose-populate,Node.js,Mongodb,Mongoose,Mongoose Populate,我知道以前有人问过这个问题,但经过数小时的研究,我尝试了几种方法来解决我的问题,但都没有成功 模式 我想做什么 我试图填充用户的赋值数组中赋值模式的作者字段 样本数据 预期结果 { _id: 5f1ef9f6039fea10c437939c, name: 'Jose Maria', createdAt: 2020-07-27T15:59:50.529Z, updatedAt: 2020-08-01T15:34:47.414Z, valuations: [ {

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

模式 我想做什么 我试图填充
用户
赋值
数组中
赋值模式
作者
字段

样本数据 预期结果

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

也尝试了,但结果相同。

参考路径应来自父级
评估。fromModel

  • 在您的模式中更改它
  • 单文档智能总体
  • 所有文件人口
注意:mongoose 5.2.9版中存在错误,
refPath
不能在嵌套数组中工作,请确保安装了最新版本


@turivishal添加了样本数据!如果您需要任何其他信息,请告诉我。@Turivshal我希望与存储在该字段中的对象ID相关联的用户文档。@Turivshal我尝试过,但发现此错误
Schema尚未为model\“fromModel\”注册\n使用mongoose.model(名称,Schema)
我需要使用refPath,因为它是我定义的3种可能的用户模型的一部分。
    await user.populate({
                        path: "valuations",
                        populate: {
                          path: "author",
                        },
                      }).execPopulate();
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();