Get the _id of inserted document in Mongo database in NodeJS

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

    Mongo sends the complete document as a callbackobject so you can simply get it from there only.

    for example

    collection.save(function(err,room){
      var newRoomId = room._id;
      });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 03:47

    @JSideris, sample code for getting insertedId.

    db.collection(COLLECTION).insertOne(data, (err, result) => {
        if (err) 
          return err;
        else 
          return result.insertedId;
      });
    
    0 讨论(0)
  • 2020-11-27 03:50

    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.

    0 讨论(0)
提交回复
热议问题