Get the _id of inserted document in Mongo database in NodeJS

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

    As ktretyak said, to get inserted document's ID best way is to use insertedId property on result object. In my case result._id didn't work so I had to use following:

    db.collection("collection-name")
      .insertOne(document)
      .then(result => {
        console.log(result.insertedId);
      })
      .catch(err => {
        // handle error
      });
    

    It's the same thing if you use callbacks.

提交回复
热议问题