I'm building a REST API with express and mongoose. I have the following schemas :
var PostSchema= new Schema({
name: String,
_comments: [{ type: Schema.Types.ObjectId, ref: 'Comment'}]
});
var CommentSchema = new Schema({
text: String,
_post: { type: Schema.Types.ObjectId, ref: 'Post'}
});
I want to add a new comment to my post :
/* POST a comment*/
router.post('/', function(req, res, next) {
var comment= new Comment(req.body);
comment.save(function (err, post) {
if (err) {
return next(err);
}
res.json(post);
});
});
It does save the comment with the following data :
{text: "bla", _post: *postId*}
However, when I retrieve my posts with populated comments :
/* GET post*/
router.get('/', function(req, res, next) {
Post.find().populate('_comments').exec(function (err, posts) {
if (err) return next(err);
res.json(posts);
});
});
The comments array is empty.
So I guess that when I'm adding a new comment to a post, I also need to add the comment id to the post.comments array and save it ? Is there a clean way to do that ?
After saving comment (in callback passed to comment.save), add it to post._comments with $addToSet. You will avoid duplicates by doing this.
Post.update({ _id: comment._post }, { $addToSet: { _comments: comment._id } }, {}).exec();