猫鼬填充子子文档

编程入门 行业动态 更新时间:2024-10-20 08:53:29
本文介绍了猫鼬填充子子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的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(itemments,{ "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.

更多推荐

猫鼬填充子子文档

本文发布于:2023-11-22 13:28:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617596.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!