Get the _id of inserted document in Mongo database in NodeJS

前端 未结 10 2008
半阙折子戏
半阙折子戏 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:32

    I actually did a console.log() for the second parameter in the callback function for insert. There is actually a lot of information returned apart from the inserted object itself. So the code below explains how you can access it's id.

    collection.insert(objToInsert, function (err, result){
        if(err)console.log(err);
        else {
            console.log(result["ops"][0]["_id"]);
            // The above statement will output the id of the 
            // inserted object
           }
    });
    

提交回复
热议问题