Get the _id of inserted document in Mongo database in NodeJS


I use NodeJS to insert documents in MongoDB. Using collection.insert I can insert a document into database like in this code:

// ...
collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId; // = ???
// ...

How can I get the _id of inserted object?

Is there any way to get the _id without getting latest object inserted _id?

Supposing that in same time a lot of people access the database, I can't be sure that the latest id is the id of object inserted.

Problem courtesy of: Ionică Bizău


There is a second parameter for the callback for collection.insert that will return the doc or docs inserted, which should have _ids.


collection.insert(objectToInsert, function(err,docsInserted){

and check the console to see what I mean.

you can also try it here:

Solution courtesy of: ξξξ


Mongo sends the complete document as a callbackobject so you can simply get it from there only.

for example,room){
  var newRoomId = room._id;
Discussion courtesy of: Saurabh Chandra Patel

I actually did a console.log() for the second parameter in the callback function for insert. There is actually a lot of information returned apart from the inserted object itself. So the code below explains how you can access it's id.

collection.insert(objToInsert, function (err, result){
    else {
        // The above statement will output the id of the 
        // inserted object
Discussion courtesy of: Sidak

A shorter way than using second parameter for the callback of collection.insert would be using objectToInsert._id that returns the _id (inside of the callback function, supposing it was a successful operation).

The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the inserted id using the original object:

collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId = objectToInsert._id; // this will return the id of object inserted
Discussion courtesy of: Ionică Bizău

Now you can use insertOne method and in promise's result.insertedId

Discussion courtesy of: ktretyak

As ktretyak said, to get inserted document's ID best way is to use insertedId property on result object. In my case result._id didn't work so I had to use following:

  .then(result => {
  .catch(err => {
    // handle error

It's the same thing if you use callbacks.

Discussion courtesy of: Serjuice

This recipe can be found in it's original form on Stack Over Flow.