Mongooseembedded式文档/ DocumentsArrays ID

在以下地址的Mongoose文档中: http : //mongoosejs.com/docs/embedded-documents.html

有一个声明:

DocumentArrays有一个特殊的方法id,它通过_id属性(每个embedded式文档都可以得到一个)来过滤embedded式文档:

考虑下面的代码片段:

post.comments.id(my_id).remove(); post.save(function (err) { // embedded comment with id `my_id` removed! }); 

我已经查看过这些数据,并且没有embedded式文档的_id ,因为这个post似乎已经证实了这一点:

如何返回最后一个push()embedded式文档

我的问题是:

文档是否正确? 如果是这样,那么我怎样才能找出'my_id'(在这个例子中)是否首先做了一个'.id(my_id)'

如果文档不正确,可以安全地使用索引作为文档数组中的一个id,或者我应该手动生成一个唯一的标识符(按照提到的post)。

而不是用像这样的json对象(这是mongoose的文档build议的方式)执行push():

 // create a comment post.comments.push({ title: 'My comment' }); 

您应该创build一个embedded对象的实际实例,然后push() 。 那么你可以直接从它中获取_id字段,因为mongoose在对象被实例化时设置它。 这是一个完整的例子:

 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(); // create a comment var mycomment = new CommentModel(); mycomment.title = "blah" console.log(mycomment._id) // <<<< This is what you're looking for post.comments.push(mycomment); post.save(function (err) { if (!err) console.log('Success!'); })