How to get the _id of inserted document in Mongo database in Node.js?

Sometimes, we want to get the _id of inserted document in Mongo database in Node.js.

In this article, we’ll look at how to get the _id of inserted document in Mongo database in Node.js.

How to get the _id of inserted document in Mongo database in Node.js?

To get the _id of inserted document in Mongo database in Node.js, we can get it from the callback of the collection insert method.

For instance, we write

collection.insert(objectToInsert, (err) => {
  if (err) {
    return;
  }
  const objectId = objectToInsert._id;
});

to call collection.insert with objectToInsert to insert the object as a document in collection.

to get the _id of the insert document from the objectToInsert._id property.

It should be available in the callback since the callback runs after the document is inserted.

Conclusion

To get the _id of inserted document in Mongo database in Node.js, we can get it from the callback of the collection insert method.