mongoose填充子子文档
我在我的MongoDB中有这个设置
项目:
title: String comments: [] // of objectId's
注释:
user: ObjectId() item: ObjectId() comment: String
这是我的Mongoose模式:
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);
这是我得到我的项目与评论的地方:
Item.find({}).populate('comments').exec(function(err, data){ if (err) return handleError(err); res.json(data); });
如何使用它的用户填充comments数组? 由于每个评论都有一个用户ObjectId()?
作为调用结果对象的完整示例:
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); }); });
从模型调用的forms对.populate()
的调用可以是文档或数组,因为它是第一个参数。 所以你循环遍历每个项目的返回结果,并调用这种方式填充每个“评论”数组。 “path”告诉函数它匹配的是什么。
这是通过使用forEach的“async”版本来完成的,因此它是非阻塞的,但是通常在响应中的所有项目都被操纵之后,不仅填充了评论,而且评论本身具有相关的“用户”细节。
还有一种方式(更简单)来做到这一点:
Item .find({}) .populate({ path: 'comments', populate: { path: 'user', model: 'users' } }) .exec(function(err, data){ if (err) return handleError(err); res.json(data); });
更简单
Item .find({}) .populate({ path: 'comments.user', model: 'users' } }) .exec(function(err, data){ if (err) return handleError(err); res.json(data); });
- Parse.com Cloud Code – 在保存之前创build另一个对象的新实例
- 我可以分配给来自JavaScript内部的玉variables吗?
- 如何使用mongoose中的聚合查询过滤$ match等于对象值
- 无法在使用把手的mandrill模板中显示javascript对象属性
- TypeError:无法读取未定义的属性'handle' – if(fn.handle && fn.set)mount_app = fn
- 压缩JSONstring? (和一般的string)
- 向Chai / Mocha提供应包含的部分密钥列表
- 如果函数的个数不知道,如何在asynchronous瀑布内迭代
- node.js将二进制string转换为数字