在MongoDB文档的子对象中_id(使用Mongoose)

我在Mongoose中创build了这样一个结构:

var Access = new Schema({ userId : { type: ObjectId, unique: true }, key : { type: String, index: true }, isOwner : { type: Boolean, index: true }, }); mongoose.model('Access', Access); var Workspace = new Schema({ name : { type: String, lowercase: true, unique: true}, activeFlag : Boolean, settings : { welcomeMessage : String, invoiceTemplate : String, longName : String, defaultCountry : String, countryId : { type: ObjectId, index: true }, }, access : [ Access ], }); mongoose.model('Workspace', Workspace); 

添加一些文件后,我看到结果:

 { "activeFlag" : true, "name" : "w7", "_id" : ObjectId("5036131f22aa014c32000006"), "access" : [ { "user": "merc", "key" : "673642387462834", "isOwner" : true, "_id" : ObjectId("5036131f22aa014c32000007") } ], "__v" : 0 } 

我对子文档中的_id感到困惑,如果我只是将其作为子结构而不是子模式添加,似乎不会发生。 所以问题:

1)这个_id从哪里来? 是mongoose的司机吗? 如果是这样,我怎样才能达到使用直Mongodb相同的行为? 只需添加一个ObjectId字段?

2)你什么时候使用一个子文档,什么时候使用一个数据结构?

3)我还没有开始我的web应用程序的严重部分。 但是,那么这个ID是不是真的 ,我的意思是 ,如果允许JsonRest访问文档中的子logging,那么这个ID是非常有用的。

谢谢你永远!

芝加哥商业交易所。

编辑:根据下面的评论删除数据重复件的答案。

要回答你的其他问题,如何在MongoDB本身中复制这个问题,你可以创build如下的文档:

 db.foo.insert( { "activeFlag" : true, "name" : "w7", "access" : [ { "userId" : ObjectId(), "key" : "673642387462834", "isOwner" : true, "_id" : ObjectId() } ], "__v" : 0 }) 

为了解释,根文档中的_id是隐含的 – 如果没有指定,它将被MongoDB添加。 但是,要获取_id到子文档中,您必须通过调用ObjectId()函数手动指定它。 我的文档看起来像这样:

 db.foo.find().pretty() { "_id" : ObjectId("50375bd0cee59c8561829edb"), "activeFlag" : true, "name" : "w7", "access" : [ { "userId" : ObjectId("50375bd0cee59c8561829ed9"), "key" : "673642387462834", "isOwner" : true, "_id" : ObjectId("50375bd0cee59c8561829eda") } ], "__v" : 0 }