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
});