我要在item.comments列表中添加评论。在响应中将其输出之前,我需要获取comment.created_by用户数据。我应该怎么做?
Item.findById(req.param('itemid'), function(err, item){ var comment = item.comments.create({ body: req.body.body , created_by: logged_in_user }); item.comments.push(comment); item.save(function(err, item){ res.json({ status: 'success', message: "You have commented on this item", //how do i populate comment.created_by here??? comment: item.comments.id(comment._id) }); }); //end item.save }); //end item.find
我需要在res.json输出中填充comment.created_by字段:
comment: item.comments.id(comment._id)
comment.created_by是我的猫鼬CommentSchema中的用户参考。它目前只给我一个用户ID,我需要它填充所有用户数据,密码和盐字段除外。
这是人们所要求的架构:
var CommentSchema = new Schema({ body : { type: String, required: true } , created_by : { type: Schema.ObjectId, ref: 'User', index: true } , created_at : { type: Date } , updated_at : { type: Date } }); var ItemSchema = new Schema({ name : { type: String, required: true, trim: true } , created_by : { type: Schema.ObjectId, ref: 'User', index: true } , comments : [CommentSchema] });
为了填充引用的子文档,您需要显式定义ID所引用的文档集合(如created_by: { type: Schema.Types.ObjectId, ref: 'User' })。
created_by: { type: Schema.Types.ObjectId, ref: 'User' }
假设已定义了此引用,并且在其他方面也对您的架构进行了很好的定义,那么您现在可以populate照常调用(例如populate('comments.created_by'))
populate
populate('comments.created_by')
概念证明代码:
// Schema var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UserSchema = new Schema({ name: String }); var CommentSchema = new Schema({ text: String, created_by: { type: Schema.Types.ObjectId, ref: 'User' } }); var ItemSchema = new Schema({ comments: [CommentSchema] }); // Connect to DB and instantiate models var db = mongoose.connect('enter your database here'); var User = db.model('User', UserSchema); var Comment = db.model('Comment', CommentSchema); var Item = db.model('Item', ItemSchema); // Find and populate Item.find({}).populate('comments.created_by').exec(function(err, items) { console.log(items[0].comments[0].created_by.name); });
最后请注意,该方法populate仅适用于查询,因此您需要先将项目传递到查询中,然后再调用它:
item.save(function(err, item) { Item.findOne(item).populate('comments.created_by').exec(function (err, item) { res.json({ status: 'success', message: "You have commented on this item", comment: item.comments.id(comment._id) }); }); });