简体   繁体   中英

is mongoose generated sub-document _id unique

Using the following mongoose schema

mongoose.Schema({
    world: String,
    color: [{ name: String }]
});

Gives me document that have sub-documents containing _id fields.

{ _id: 'a9ec8475bf0d285e10ca8d42'
  world: 'matrix', 
  color: [
    { name: 'blue',  _id: '4a8c0e12135fa32e13db9ce9' },
    { name: 'red',   _id: '4a8c0a62254cd32e13db4ad8' },
    { name: 'white', _id: '4a8c04e2687ea32e13db1da7' }
]

I want to know if each of these sub-documents _id are unique across all documents, or only across the nested level it is in.

Edit : the sub-document doesn't refer to another collection, it's created with the plain mongoose schema above.

I assume the sub-document references another collection. If my assumption is right then the nested documents you have are only unique only on the nested level.

This is an issue with Mongoose. Mongoose creates schemas for each of those nested objects behind the scenes. That means the _id is only unquie on the nested level.

Look at this previous question on how to prevent this from happening

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM