Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 975
Ionică Bizău Avatar asked Jan 23 '13 13:01

Ionică Bizău


People also ask

How does the value of _id get assigned to a document MongoDB?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. This also applies to documents inserted through update operations with upsert: true.

How can I see last inserted record in MongoDB?

To get last inserted document, use sort() along with limit(1).


2 Answers

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 }); 
like image 73
Ionică Bizău Avatar answered Sep 20 '22 15:09

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.

Try:

collection.insert(objectToInsert, function(err,docsInserted){     console.log(docsInserted); }); 

and check the console to see what I mean.

like image 44
georgedyer Avatar answered Sep 20 '22 15:09

georgedyer