I am adding a comment to an item.comments list. I need to get the comment.created_by user data before I output it in the response. How should I do this?
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
I need to populate the comment.created_by field here in my res.json output:
comment: item.comments.id(comment._id)
comment.created_by is a user reference in my mongoose CommentSchema. It currently is only giving me a user id, I need it populated with all the user data, except for password and salt fields.
Here is the schema as people have asked:
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]
});
In order to populate referenced subdocuments, you need to explicitly define the document collection to which the ID references to (like
created_by: { type: Schema.Types.ObjectId, ref: 'User' }).Given this reference is defined and your schema is otherwise well defined as well, you can now just call
populateas usual (e.g.populate('comments.created_by'))Proof of concept code:
Finally note that
populateworks only for queries so you need to first pass your item into a query and then call it: