0

我正在使用 Mongoose 和 Nodejs 编写一个论坛模块。

我有一个 ForumPost 对象的集合,它们有一个属性“comments”,它是一个包含引用属性“author”的猫鼬模式,它引用了一个用户模型。我在为“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 评论数组中对象的“作者”字段?

4

1 回答 1

0

因为您没有进行任何嵌套填充,所以您可以在一次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);
    });
于 2015-12-28T16:05:13.037 回答