如何在 Mongoose 中填充嵌套实体?

How to populate nested entity in Mongoose?

我有这样的模型:

const UserSchema = new mongoose.Schema({
  name: String,
  workspaces: [
    {
      workspace: {
        type: mongoose.Schema.ObjectId,
      },
      owner: Boolean
    }
  ]
});

const WorkspaceSchema = new mongoose.Schema({
  title: String,
  description: String 
});

我想像这样填充用户记录:

{
  name: "John",
  workspaces: [{
    workspace: {
      title: "First space",
      description: "About space#1"
    },
    owner: true
  }, {
    workspace: {
      title: "Second space",
      description: "About space#2"
    },
    owner: false
  }]
}

我尝试通过填充方法做到这一点:

const user = await User
  .findOne(query)
  .populate({
    path: 'workspaces',
    populate: {
      path: 'workspace',
      model: 'Workspace'
    }
  });

这是不正确的。我搜索了这样的案例,但没有找到类似的东西。所有其他示例都不包括 属性 ,例如我的布尔值 "owner".

使用深度填充

安装:

npm i mongoose-deep-populate

用法:

var deepPopulate = require('mongoose-deep-populate')(mongoose);

User.deepPopulate(users, 'workspaces.workspace')
.then(function(err, data) {
    console.log(data);
});

阅读更多:https://www.npmjs.com/package/mongoose-deep-populate

希望这能解决您的问题。

我建议您在用户架构声明中添加对工作区模型的引用:

 workspace: {
    type: mongoose.Schema.ObjectId,
    ref: "Workspace"
 }

此外,您可能搞砸了 populate 方法,因为 workspaces 数组本身不包含对外部对象的引用。 您可能应该像这样使用此方法:

const user = await User
  .findOne(query)
  .populate("workspaces.workspace");

或者,如果您需要除路径之外的任何其他选项,请使用选项对象:

const user = await User
  .findOne(query)
  .populate({
    path: "workspaces.workspace", ...
  });