tonyf
tonyf

Reputation: 35557

Obtain Newly Created Object ID in MongoDB

I have the following MongoDB query and I am using the mongodb node.js driver to connect:

db.collection('employee').insertOne(employeeObj).then(result => {
    console.log(result);
    res.send(result);
}).catch(function (err) {
    console.log("ERROR: ", err);
});

From the above, I would like to obtain the newly created employee's Object _Id but when I console log the result, I get:

Object { n: 1, ok: 1 }

Using the above query, how can I also include the new _id just created within the returned result?

Upvotes: 0

Views: 2132

Answers (3)

Sid
Sid

Reputation: 14896

The result object should contain a insertedId property which is driver generated ObjectId for the insert operation.

Try to log result.insertedId to check the id, and also you should have the inserted object in the ops property.

Upvotes: 2

Anand Undavia
Anand Undavia

Reputation: 3543

The _id field would be added to the employeeObj once it is added to the collection.

This is from the docs:

insertOne(doc, options, callback)

Inserts a single document into MongoDB. If documents passed in do not contain the _id field, one will be added to each of the documents missing it by the driver, mutating the document. This behavior can be overridden by setting the forceServerObjectId flag.

Just change the code to:

db.collection('employee').insertOne(employee).then(result => {
    console.log(employee._id);
    res.send({employee, result});
}).catch(function (err) {
    console.log("ERROR: ", err);
});

This might be helpful too.

Upvotes: 0

Supradeep
Supradeep

Reputation: 161

I assume you are using mongoose package. If you want to create custom _id for your document you can use

var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');

and pass it with your employee object.

more info go here.

Upvotes: 0

Related Questions