Ionică Bizău Ionică Bizău - 2 months ago 17
Node.js Question

Get the _id of inserted document in Mongo database in NodeJS

I use NodeJS to insert documents in MongoDB. Using

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
of inserted object?

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

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.


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: