4

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

2 Answers 2

3

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: '...' });
Sign up to request clarification or add additional context in comments.

1 Comment

I tried the third option but for some reason it says ObjectId is not defined.
0
public class BatteryDetails {
    /**
     * The batteryId of the Battery.
     */
    private String batteryId;
public BatteryDetails() {
        batteryId= new ObjectId().toString();
    }
}

This line (batteryId= new ObjectId().toString();) creates a objectId for the sub document.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.