首页 > 解决方案 > 如何在猫鼬的嵌入式文档中填充字段?

问题描述

我有一个类似这样的模型“帖子”

{
   // Some other fields
   comments: [
    new mongoose.Schema({
      content: {
        type: String,
        required: [true, "Content for a comment is required."],
      },
      author: {
        type: mongoose.Types.ObjectId,
        ref: "User",
        required: [true, "Author for a comment is required."],
      },
    }),
}

在获取帖子后,我无法找到一种填充author内部字段的方法。comment我该怎么做?

标签: node.jsmongodbexpressmongoosemongodb-query

解决方案


尝试跨多个级别填充

Post.find({ }).populate({
    path: 'comments',
    populate: { path: 'author' }
});

推荐阅读