Get the _id of inserted document in Mongo database in NodeJS

前端 未结 10 1978
半阙折子戏
半阙折子戏 2020-11-27 02:53

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

// ...
collection.         


        
10条回答
  •  无人及你
    2020-11-27 03:43

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

提交回复
热议问题