而不是对像这样的json对象执行push()(猫鼬文档建议的方式):
// create a commentpost.comments.push({ title: 'My comment' });
您应该创建一个嵌入式对象的实际实例
push(),而不是实际实例。然后,您可以直接从中获取_id字段,因为猫鼬在实例化对象时对其进行设置。这是一个完整的示例:
var mongoose = require('mongoose')var Schema = mongoose.Schemavar ObjectId = Schema.ObjectIdmongoose.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();// create a commentvar mycomment = new CommentModel();mycomment.title = "blah"console.log(mycomment._id) // <<<< This is what you're looking forpost.comments.push(mycomment);post.save(function (err) { if (!err) console.log('Success!');})
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)