猫鼬填充子子文档 [英] Mongoose populate sub-sub document

查看:74
本文介绍了猫鼬填充子子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MongoDB中有此设置

I have this setup in my MongoDB

项目:

title: String
comments: [] // of objectId's

评论:

user: ObjectId()
item: ObjectId()
comment: String

这是我的猫鼬模式:

itemSchema = mongoose.Schema({
    title: String,
    comments: [{ type: Schema.Types.ObjectId, ref: 'comments' }],
});

Item = mongoose.model('items', itemSchema);

commentSchema = mongoose.Schema({
    comment: String,
    user: { type: Schema.Types.ObjectId, ref: 'users' },
});

Comment = mongoose.model('comments', commentSchema);

在这里我可以收到我的物品以及评论:

This is where I get my items along with the comments:

Item.find({}).populate('comments').exec(function(err, data){
    if (err) return handleError(err);
    res.json(data);
});

如何用各自的用户填充评论数组?由于每个注释都有一个用户ObjectId()?

How do I populate the comments array with it's respective user? Since each comment has a user ObjectId()?

推荐答案

作为一个完整的示例,在结果对象上进行填充:

As a complete example calling populate on the result objects:

Item.find({}).populate("comments").exec(function(err,data) {
    if (err) return handleError(err);

    async.forEach(data,function(item,callback) {
        User.populate(item.comments,{ "path": "user" },function(err,output) {
            if (err) throw err; // or do something

            callback();
        });
    }, function(err) {
        res.json(data);
    });

});

以从模型调用的形式调用 .populate() 文档或数组作为第一个参数.因此,您遍历每个项目的返回结果,并以这种方式在每个评论"数组上进行填充. 路径"告诉函数它匹配什么.

The call to .populate() in the form invoked from the model takes either a document or an array as it's first argument. So you loop through the returned results for each item and call populate this way on each "comments" array. The "path" tells the function what it is matching.

这是使用forEach的异步"版本完成的,因此它是非阻塞的,但是通常,在所有操作之后,响应中的所有项目不仅填充了注释,而且注释本身也具有相关的用户"详细信息.

This is done using the "async" version of forEach so it is non-blocking, but generally after all the manipulation all of the items in the response are not only populated with comments but the comments themselves have the related "user" details.

这篇关于猫鼬填充子子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆