填充字段,该字段是单个查询中嵌入数组的属性

Populating a field which is a property of an embedded array in a single query

本文关键字:字段 数组 属性 查询 单个 填充      更新时间:2023-09-26

我正在使用Mongoose&Nodejs。

我有一个ForumPost对象的集合,它有一个属性"comments",这是一个包含引用属性"author"的猫鼬模式,它引用了一个User模型。我在为"comments"数组中的每个项填充"author"属性时遇到了问题。

以下是ForumPost对象定义:

var ForumPost = db.model("ForumPost", {
    author: { type: Schema.Types.ObjectId, ref: "User", required: true, default: null, select: true},
    comments: [new db.Schema({
        author: { type: Schema.Types.ObjectId, ref: "User" },
        comment: { type: String, default: ""},
    })]
});

当我从数据库中提取这些内容时,我会填充论坛帖子的"作者"字段,这很好,因为这是一个基本的填充操作。

今天早上,我一直试图填充评论数组的"作者"字段,但没有成功,我的最新尝试发布在下面。

我使用以下查询:

ForumPost.findOne({alliance_id: alliance._id, _id: post_id})
                        .populate("author")
                        .populate({ 
                             path: 'comments',
                             populate: {
                               path: 'comments.author',
                               model: 'User'
                             } 
                          })
                        .select("comments")
                        .exec(function(error, post) {
                return res.json(post);
            });

这是否可以在单个查询中填充ForumPost注释数组中对象的"作者"字段?

因为您没有执行任何嵌套填充,所以您可以在单个populate调用中包括这两个路径:

ForumPost.findOne({alliance_id: alliance._id, _id: post_id})
    .populate('author comments.author')
    .select('author comments')
    .exec(function(error, post) {
        return res.json(post);
    });