Instead of doing push () with a json object like this (the method suggested by mongoose docs):
// create a comment post.comments.push({ title: 'My comment' });
Instead, you should create the actual instance of your embedded object and push() . Then you can directly capture the _id field, because the mongoose sets it when the object is created. Here is a complete example:
var mongoose = require('mongoose') var Schema = mongoose.Schema var ObjectId = Schema.ObjectId mongoose.connect('mongodb://localhost/testjs'); var Comment = new Schema({ title : String , body : String , date : Date }); var BlogPost = new Schema({ author : ObjectId , title : String , body : String , date : Date , comments : [Comment] , meta : { votes : Number , favs : Number } }); mongoose.model('Comment', Comment); mongoose.model('BlogPost', BlogPost); var BlogPost = mongoose.model('BlogPost'); var CommentModel = mongoose.model('Comment') var post = new BlogPost();
source share