Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatically add object id on subdocument when updating in mongodb

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

like image 287
kennanwho Avatar asked Sep 18 '25 11:09

kennanwho


1 Answers

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: '...' });
like image 54
Dario Avatar answered Sep 20 '25 01:09

Dario