LearnBoost/mongoose — Issue #692: Adding a new embedded document
Author: Vovan222
Created: 2012-01-21 13:37:52+00:00
State: open

I have the following BlogPost and Comment schema:

var Comments = new Schema({
_id : ObjectId,
title : String,
body : String
});

var BlogPost = new Schema({
_id : ObjectId,
title : String,
body : String,
comments : [Comments]
});

var Post = mongoose.model('BlogPost', BlogPost);

I need to add a new comment into the post collection. When I do like this:

app.post('/post/:id/addcomment', function (req, res){
var postId = req.param.id;
Post.findById(postId, function (err, doc) {
if (doc) {
doc.cpmments.push({title: 'empty title', body: 'empty body'});
doc.save(function (err) {

});
}
});
});

I get the following post structure in MongoDB:

{
_id: ObjectId(.....),
title: 'Some post title',
body: 'some post body',
comments: [
{
title: 'empty title',
body: 'empty body'
}
]
}

As you can see the new comment is inserted successfully but it does not have ObjectId. How can I generate ObjectId automatically when a new comment is inserted?