Document:
[{
_id: "58aaf5f87fa9df48753fa04b",
username: "test",
stores: [ ]
}]
I want to add new objects in the stores element. IS there any way to automatically add a new _id for each new object I add? I'm using the version 2.6
Using mongodb
native driver not, it won't add an _id
to sub-documents for you.
But if you use mongoose-odm
it will add the _id
automatically on an array of sub-documents.
If you use mongodb
native driver you can just add and initialize a _id: ObjectID()
field before save it:
const ObjectID = require('mongodb').ObjectID
const doc = {
_id: new ObjectID(),
username: "test",
stores: [ ]
}
doc.stores.push({ _id: new ObjectID(), value: '...' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With