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); });