Get the _id of inserted document in Mongo database in NodeJS












84















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



// ...
collection.insert(objectToInsert, function(err){
if (err) return;
// Object inserted successfully.
var objectId; // = ???
});
// ...


How can I get the _id of inserted object?



Is there any way to get the _id without getting latest object inserted _id?



Supposing that in same time a lot of people access the database, I can't be sure that the latest id is the id of object inserted.










share|improve this question



























    84















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



    // ...
    collection.insert(objectToInsert, function(err){
    if (err) return;
    // Object inserted successfully.
    var objectId; // = ???
    });
    // ...


    How can I get the _id of inserted object?



    Is there any way to get the _id without getting latest object inserted _id?



    Supposing that in same time a lot of people access the database, I can't be sure that the latest id is the id of object inserted.










    share|improve this question

























      84












      84








      84


      11






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



      // ...
      collection.insert(objectToInsert, function(err){
      if (err) return;
      // Object inserted successfully.
      var objectId; // = ???
      });
      // ...


      How can I get the _id of inserted object?



      Is there any way to get the _id without getting latest object inserted _id?



      Supposing that in same time a lot of people access the database, I can't be sure that the latest id is the id of object inserted.










      share|improve this question














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



      // ...
      collection.insert(objectToInsert, function(err){
      if (err) return;
      // Object inserted successfully.
      var objectId; // = ???
      });
      // ...


      How can I get the _id of inserted object?



      Is there any way to get the _id without getting latest object inserted _id?



      Supposing that in same time a lot of people access the database, I can't be sure that the latest id is the id of object inserted.







      javascript node.js mongodb






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 23 '13 at 13:59









      Ionică BizăuIonică Bizău

      59.3k57202351




      59.3k57202351
























          8 Answers
          8






          active

          oldest

          votes


















          78














          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.






          share|improve this answer





















          • 4





            Callback actually returns array of documents inserted. So, if you have inserted a single document then you can access the inserted record as below. collection.insert({name:"David", title:"About MongoDB"}, function(err, records){ console.log("Record added as "+records[0]._id); }); Ref: mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

            – Rohit Singh Sengar
            Jun 16 '14 at 11:47








          • 2





            The Callbacks API has changed: mongodb.github.io/node-mongodb-native/2.0/api/…

            – tenbits
            May 13 '15 at 13:10











          • link does not lead anywhere useful

            – davidhadas
            Apr 8 '16 at 21:42











          • I don't know if this is general or only works in meteor, but when you call collection.insert(object), it returns the id of the inserted object right away.

            – vantesllar
            Oct 30 '16 at 20:45






          • 4





            docsInserted does not return an _id for me. it returns for me { "ok": 1, "n": 1, "opTime": { "ts": "6361004504208375809", "t": 5 }, "electionId": "7fffffff0000000000000005" }

            – user1709076
            Dec 6 '16 at 15:08



















          77














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





          share|improve this answer





















          • 4





            Very insightful thank you. Couldn't find this information anywhere else since the change in callback parameters.

            – Brad Hein
            Jul 26 '15 at 18:39











          • @BradHein You're welcome! Probably the MongoDB driver modifies the object reference, so it gets modified here too. :)

            – Ionică Bizău
            Jul 27 '15 at 4:25











          • Your code is wrong, where you say var objectId = objectToInsert._id; you meant to say var objectId = objectInserted._id;

            – Andy Lorenz
            Jul 28 '15 at 13:48








          • 3





            @AndyLorenz What is objectInserted? I guess you're missing exactly the point of this answer: the Mongo driver appends the _id field to the original object. I edited the answer to use objectToInsert everywhere. Hope the things are clearer now. :)

            – Ionică Bizău
            Jul 28 '15 at 18:50






          • 1





            NOTE: insert() is deprecated. Use insertOne() instead

            – evilReiko
            Nov 24 '16 at 12:07



















          11














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





          share|improve this answer





















          • 1





            thanks :) this worked for me

            – Aayushi
            Jul 13 '17 at 9:50











          • this should be marked as the correct response

            – user1709076
            Jul 27 '17 at 12:04



















          10














          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.






          share|improve this answer































            5














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





            share|improve this answer































              4














              Now you can use insertOne method and in promise's result.insertedId






              share|improve this answer
























              • Could you provide a code example? Where does this result object come from?

                – JSideris
                Sep 20 '16 at 22:00











              • @JSideris, as you can see in the specification method insertOne(), this method accepts three parameters (doc, options, callback). The third parameter - a callback, which takes two parameters (error, result). And result - this is what you are looking for.

                – ktretyak
                Sep 21 '16 at 0:10





















              1














              @JSideris, sample code for getting insertedId.



              db.collection(COLLECTION).insertOne(data, (err, result) => {
              if (err)
              return err;
              else
              return result.insertedId;
              });





              share|improve this answer































                0














                if you want to take "_id" use simpley



                result.insertedId.toString() 


                // toString will convert from hex






                share|improve this answer
























                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14481521%2fget-the-id-of-inserted-document-in-mongo-database-in-nodejs%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  8 Answers
                  8






                  active

                  oldest

                  votes








                  8 Answers
                  8






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  78














                  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.






                  share|improve this answer





















                  • 4





                    Callback actually returns array of documents inserted. So, if you have inserted a single document then you can access the inserted record as below. collection.insert({name:"David", title:"About MongoDB"}, function(err, records){ console.log("Record added as "+records[0]._id); }); Ref: mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

                    – Rohit Singh Sengar
                    Jun 16 '14 at 11:47








                  • 2





                    The Callbacks API has changed: mongodb.github.io/node-mongodb-native/2.0/api/…

                    – tenbits
                    May 13 '15 at 13:10











                  • link does not lead anywhere useful

                    – davidhadas
                    Apr 8 '16 at 21:42











                  • I don't know if this is general or only works in meteor, but when you call collection.insert(object), it returns the id of the inserted object right away.

                    – vantesllar
                    Oct 30 '16 at 20:45






                  • 4





                    docsInserted does not return an _id for me. it returns for me { "ok": 1, "n": 1, "opTime": { "ts": "6361004504208375809", "t": 5 }, "electionId": "7fffffff0000000000000005" }

                    – user1709076
                    Dec 6 '16 at 15:08
















                  78














                  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.






                  share|improve this answer





















                  • 4





                    Callback actually returns array of documents inserted. So, if you have inserted a single document then you can access the inserted record as below. collection.insert({name:"David", title:"About MongoDB"}, function(err, records){ console.log("Record added as "+records[0]._id); }); Ref: mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

                    – Rohit Singh Sengar
                    Jun 16 '14 at 11:47








                  • 2





                    The Callbacks API has changed: mongodb.github.io/node-mongodb-native/2.0/api/…

                    – tenbits
                    May 13 '15 at 13:10











                  • link does not lead anywhere useful

                    – davidhadas
                    Apr 8 '16 at 21:42











                  • I don't know if this is general or only works in meteor, but when you call collection.insert(object), it returns the id of the inserted object right away.

                    – vantesllar
                    Oct 30 '16 at 20:45






                  • 4





                    docsInserted does not return an _id for me. it returns for me { "ok": 1, "n": 1, "opTime": { "ts": "6361004504208375809", "t": 5 }, "electionId": "7fffffff0000000000000005" }

                    – user1709076
                    Dec 6 '16 at 15:08














                  78












                  78








                  78







                  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.






                  share|improve this answer















                  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.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 1 '18 at 17:15

























                  answered Jan 23 '13 at 14:13









                  georgedyergeorgedyer

                  2,3841725




                  2,3841725








                  • 4





                    Callback actually returns array of documents inserted. So, if you have inserted a single document then you can access the inserted record as below. collection.insert({name:"David", title:"About MongoDB"}, function(err, records){ console.log("Record added as "+records[0]._id); }); Ref: mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

                    – Rohit Singh Sengar
                    Jun 16 '14 at 11:47








                  • 2





                    The Callbacks API has changed: mongodb.github.io/node-mongodb-native/2.0/api/…

                    – tenbits
                    May 13 '15 at 13:10











                  • link does not lead anywhere useful

                    – davidhadas
                    Apr 8 '16 at 21:42











                  • I don't know if this is general or only works in meteor, but when you call collection.insert(object), it returns the id of the inserted object right away.

                    – vantesllar
                    Oct 30 '16 at 20:45






                  • 4





                    docsInserted does not return an _id for me. it returns for me { "ok": 1, "n": 1, "opTime": { "ts": "6361004504208375809", "t": 5 }, "electionId": "7fffffff0000000000000005" }

                    – user1709076
                    Dec 6 '16 at 15:08














                  • 4





                    Callback actually returns array of documents inserted. So, if you have inserted a single document then you can access the inserted record as below. collection.insert({name:"David", title:"About MongoDB"}, function(err, records){ console.log("Record added as "+records[0]._id); }); Ref: mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

                    – Rohit Singh Sengar
                    Jun 16 '14 at 11:47








                  • 2





                    The Callbacks API has changed: mongodb.github.io/node-mongodb-native/2.0/api/…

                    – tenbits
                    May 13 '15 at 13:10











                  • link does not lead anywhere useful

                    – davidhadas
                    Apr 8 '16 at 21:42











                  • I don't know if this is general or only works in meteor, but when you call collection.insert(object), it returns the id of the inserted object right away.

                    – vantesllar
                    Oct 30 '16 at 20:45






                  • 4





                    docsInserted does not return an _id for me. it returns for me { "ok": 1, "n": 1, "opTime": { "ts": "6361004504208375809", "t": 5 }, "electionId": "7fffffff0000000000000005" }

                    – user1709076
                    Dec 6 '16 at 15:08








                  4




                  4





                  Callback actually returns array of documents inserted. So, if you have inserted a single document then you can access the inserted record as below. collection.insert({name:"David", title:"About MongoDB"}, function(err, records){ console.log("Record added as "+records[0]._id); }); Ref: mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

                  – Rohit Singh Sengar
                  Jun 16 '14 at 11:47







                  Callback actually returns array of documents inserted. So, if you have inserted a single document then you can access the inserted record as below. collection.insert({name:"David", title:"About MongoDB"}, function(err, records){ console.log("Record added as "+records[0]._id); }); Ref: mongodb.github.io/node-mongodb-native/markdown-docs/insert.html

                  – Rohit Singh Sengar
                  Jun 16 '14 at 11:47






                  2




                  2





                  The Callbacks API has changed: mongodb.github.io/node-mongodb-native/2.0/api/…

                  – tenbits
                  May 13 '15 at 13:10





                  The Callbacks API has changed: mongodb.github.io/node-mongodb-native/2.0/api/…

                  – tenbits
                  May 13 '15 at 13:10













                  link does not lead anywhere useful

                  – davidhadas
                  Apr 8 '16 at 21:42





                  link does not lead anywhere useful

                  – davidhadas
                  Apr 8 '16 at 21:42













                  I don't know if this is general or only works in meteor, but when you call collection.insert(object), it returns the id of the inserted object right away.

                  – vantesllar
                  Oct 30 '16 at 20:45





                  I don't know if this is general or only works in meteor, but when you call collection.insert(object), it returns the id of the inserted object right away.

                  – vantesllar
                  Oct 30 '16 at 20:45




                  4




                  4





                  docsInserted does not return an _id for me. it returns for me { "ok": 1, "n": 1, "opTime": { "ts": "6361004504208375809", "t": 5 }, "electionId": "7fffffff0000000000000005" }

                  – user1709076
                  Dec 6 '16 at 15:08





                  docsInserted does not return an _id for me. it returns for me { "ok": 1, "n": 1, "opTime": { "ts": "6361004504208375809", "t": 5 }, "electionId": "7fffffff0000000000000005" }

                  – user1709076
                  Dec 6 '16 at 15:08













                  77














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





                  share|improve this answer





















                  • 4





                    Very insightful thank you. Couldn't find this information anywhere else since the change in callback parameters.

                    – Brad Hein
                    Jul 26 '15 at 18:39











                  • @BradHein You're welcome! Probably the MongoDB driver modifies the object reference, so it gets modified here too. :)

                    – Ionică Bizău
                    Jul 27 '15 at 4:25











                  • Your code is wrong, where you say var objectId = objectToInsert._id; you meant to say var objectId = objectInserted._id;

                    – Andy Lorenz
                    Jul 28 '15 at 13:48








                  • 3





                    @AndyLorenz What is objectInserted? I guess you're missing exactly the point of this answer: the Mongo driver appends the _id field to the original object. I edited the answer to use objectToInsert everywhere. Hope the things are clearer now. :)

                    – Ionică Bizău
                    Jul 28 '15 at 18:50






                  • 1





                    NOTE: insert() is deprecated. Use insertOne() instead

                    – evilReiko
                    Nov 24 '16 at 12:07
















                  77














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





                  share|improve this answer





















                  • 4





                    Very insightful thank you. Couldn't find this information anywhere else since the change in callback parameters.

                    – Brad Hein
                    Jul 26 '15 at 18:39











                  • @BradHein You're welcome! Probably the MongoDB driver modifies the object reference, so it gets modified here too. :)

                    – Ionică Bizău
                    Jul 27 '15 at 4:25











                  • Your code is wrong, where you say var objectId = objectToInsert._id; you meant to say var objectId = objectInserted._id;

                    – Andy Lorenz
                    Jul 28 '15 at 13:48








                  • 3





                    @AndyLorenz What is objectInserted? I guess you're missing exactly the point of this answer: the Mongo driver appends the _id field to the original object. I edited the answer to use objectToInsert everywhere. Hope the things are clearer now. :)

                    – Ionică Bizău
                    Jul 28 '15 at 18:50






                  • 1





                    NOTE: insert() is deprecated. Use insertOne() instead

                    – evilReiko
                    Nov 24 '16 at 12:07














                  77












                  77








                  77







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





                  share|improve this answer















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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 29 '15 at 9:23

























                  answered Jan 23 '13 at 14:29









                  Ionică BizăuIonică Bizău

                  59.3k57202351




                  59.3k57202351








                  • 4





                    Very insightful thank you. Couldn't find this information anywhere else since the change in callback parameters.

                    – Brad Hein
                    Jul 26 '15 at 18:39











                  • @BradHein You're welcome! Probably the MongoDB driver modifies the object reference, so it gets modified here too. :)

                    – Ionică Bizău
                    Jul 27 '15 at 4:25











                  • Your code is wrong, where you say var objectId = objectToInsert._id; you meant to say var objectId = objectInserted._id;

                    – Andy Lorenz
                    Jul 28 '15 at 13:48








                  • 3





                    @AndyLorenz What is objectInserted? I guess you're missing exactly the point of this answer: the Mongo driver appends the _id field to the original object. I edited the answer to use objectToInsert everywhere. Hope the things are clearer now. :)

                    – Ionică Bizău
                    Jul 28 '15 at 18:50






                  • 1





                    NOTE: insert() is deprecated. Use insertOne() instead

                    – evilReiko
                    Nov 24 '16 at 12:07














                  • 4





                    Very insightful thank you. Couldn't find this information anywhere else since the change in callback parameters.

                    – Brad Hein
                    Jul 26 '15 at 18:39











                  • @BradHein You're welcome! Probably the MongoDB driver modifies the object reference, so it gets modified here too. :)

                    – Ionică Bizău
                    Jul 27 '15 at 4:25











                  • Your code is wrong, where you say var objectId = objectToInsert._id; you meant to say var objectId = objectInserted._id;

                    – Andy Lorenz
                    Jul 28 '15 at 13:48








                  • 3





                    @AndyLorenz What is objectInserted? I guess you're missing exactly the point of this answer: the Mongo driver appends the _id field to the original object. I edited the answer to use objectToInsert everywhere. Hope the things are clearer now. :)

                    – Ionică Bizău
                    Jul 28 '15 at 18:50






                  • 1





                    NOTE: insert() is deprecated. Use insertOne() instead

                    – evilReiko
                    Nov 24 '16 at 12:07








                  4




                  4





                  Very insightful thank you. Couldn't find this information anywhere else since the change in callback parameters.

                  – Brad Hein
                  Jul 26 '15 at 18:39





                  Very insightful thank you. Couldn't find this information anywhere else since the change in callback parameters.

                  – Brad Hein
                  Jul 26 '15 at 18:39













                  @BradHein You're welcome! Probably the MongoDB driver modifies the object reference, so it gets modified here too. :)

                  – Ionică Bizău
                  Jul 27 '15 at 4:25





                  @BradHein You're welcome! Probably the MongoDB driver modifies the object reference, so it gets modified here too. :)

                  – Ionică Bizău
                  Jul 27 '15 at 4:25













                  Your code is wrong, where you say var objectId = objectToInsert._id; you meant to say var objectId = objectInserted._id;

                  – Andy Lorenz
                  Jul 28 '15 at 13:48







                  Your code is wrong, where you say var objectId = objectToInsert._id; you meant to say var objectId = objectInserted._id;

                  – Andy Lorenz
                  Jul 28 '15 at 13:48






                  3




                  3





                  @AndyLorenz What is objectInserted? I guess you're missing exactly the point of this answer: the Mongo driver appends the _id field to the original object. I edited the answer to use objectToInsert everywhere. Hope the things are clearer now. :)

                  – Ionică Bizău
                  Jul 28 '15 at 18:50





                  @AndyLorenz What is objectInserted? I guess you're missing exactly the point of this answer: the Mongo driver appends the _id field to the original object. I edited the answer to use objectToInsert everywhere. Hope the things are clearer now. :)

                  – Ionică Bizău
                  Jul 28 '15 at 18:50




                  1




                  1





                  NOTE: insert() is deprecated. Use insertOne() instead

                  – evilReiko
                  Nov 24 '16 at 12:07





                  NOTE: insert() is deprecated. Use insertOne() instead

                  – evilReiko
                  Nov 24 '16 at 12:07











                  11














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





                  share|improve this answer





















                  • 1





                    thanks :) this worked for me

                    – Aayushi
                    Jul 13 '17 at 9:50











                  • this should be marked as the correct response

                    – user1709076
                    Jul 27 '17 at 12:04
















                  11














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





                  share|improve this answer





















                  • 1





                    thanks :) this worked for me

                    – Aayushi
                    Jul 13 '17 at 9:50











                  • this should be marked as the correct response

                    – user1709076
                    Jul 27 '17 at 12:04














                  11












                  11








                  11







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





                  share|improve this answer















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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jun 19 '15 at 0:24

























                  answered Jun 19 '15 at 0:19









                  SidakSidak

                  147110




                  147110








                  • 1





                    thanks :) this worked for me

                    – Aayushi
                    Jul 13 '17 at 9:50











                  • this should be marked as the correct response

                    – user1709076
                    Jul 27 '17 at 12:04














                  • 1





                    thanks :) this worked for me

                    – Aayushi
                    Jul 13 '17 at 9:50











                  • this should be marked as the correct response

                    – user1709076
                    Jul 27 '17 at 12:04








                  1




                  1





                  thanks :) this worked for me

                  – Aayushi
                  Jul 13 '17 at 9:50





                  thanks :) this worked for me

                  – Aayushi
                  Jul 13 '17 at 9:50













                  this should be marked as the correct response

                  – user1709076
                  Jul 27 '17 at 12:04





                  this should be marked as the correct response

                  – user1709076
                  Jul 27 '17 at 12:04











                  10














                  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.






                  share|improve this answer




























                    10














                    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.






                    share|improve this answer


























                      10












                      10








                      10







                      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.






                      share|improve this answer













                      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.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Feb 24 '17 at 21:45









                      SerjuiceSerjuice

                      321210




                      321210























                          5














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





                          share|improve this answer




























                            5














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





                            share|improve this answer


























                              5












                              5








                              5







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





                              share|improve this answer













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






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Sep 2 '14 at 5:25









                              Saurabh Chandra PatelSaurabh Chandra Patel

                              6,01815162




                              6,01815162























                                  4














                                  Now you can use insertOne method and in promise's result.insertedId






                                  share|improve this answer
























                                  • Could you provide a code example? Where does this result object come from?

                                    – JSideris
                                    Sep 20 '16 at 22:00











                                  • @JSideris, as you can see in the specification method insertOne(), this method accepts three parameters (doc, options, callback). The third parameter - a callback, which takes two parameters (error, result). And result - this is what you are looking for.

                                    – ktretyak
                                    Sep 21 '16 at 0:10


















                                  4














                                  Now you can use insertOne method and in promise's result.insertedId






                                  share|improve this answer
























                                  • Could you provide a code example? Where does this result object come from?

                                    – JSideris
                                    Sep 20 '16 at 22:00











                                  • @JSideris, as you can see in the specification method insertOne(), this method accepts three parameters (doc, options, callback). The third parameter - a callback, which takes two parameters (error, result). And result - this is what you are looking for.

                                    – ktretyak
                                    Sep 21 '16 at 0:10
















                                  4












                                  4








                                  4







                                  Now you can use insertOne method and in promise's result.insertedId






                                  share|improve this answer













                                  Now you can use insertOne method and in promise's result.insertedId







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jul 28 '16 at 8:34









                                  ktretyakktretyak

                                  3,99942141




                                  3,99942141













                                  • Could you provide a code example? Where does this result object come from?

                                    – JSideris
                                    Sep 20 '16 at 22:00











                                  • @JSideris, as you can see in the specification method insertOne(), this method accepts three parameters (doc, options, callback). The third parameter - a callback, which takes two parameters (error, result). And result - this is what you are looking for.

                                    – ktretyak
                                    Sep 21 '16 at 0:10





















                                  • Could you provide a code example? Where does this result object come from?

                                    – JSideris
                                    Sep 20 '16 at 22:00











                                  • @JSideris, as you can see in the specification method insertOne(), this method accepts three parameters (doc, options, callback). The third parameter - a callback, which takes two parameters (error, result). And result - this is what you are looking for.

                                    – ktretyak
                                    Sep 21 '16 at 0:10



















                                  Could you provide a code example? Where does this result object come from?

                                  – JSideris
                                  Sep 20 '16 at 22:00





                                  Could you provide a code example? Where does this result object come from?

                                  – JSideris
                                  Sep 20 '16 at 22:00













                                  @JSideris, as you can see in the specification method insertOne(), this method accepts three parameters (doc, options, callback). The third parameter - a callback, which takes two parameters (error, result). And result - this is what you are looking for.

                                  – ktretyak
                                  Sep 21 '16 at 0:10







                                  @JSideris, as you can see in the specification method insertOne(), this method accepts three parameters (doc, options, callback). The third parameter - a callback, which takes two parameters (error, result). And result - this is what you are looking for.

                                  – ktretyak
                                  Sep 21 '16 at 0:10













                                  1














                                  @JSideris, sample code for getting insertedId.



                                  db.collection(COLLECTION).insertOne(data, (err, result) => {
                                  if (err)
                                  return err;
                                  else
                                  return result.insertedId;
                                  });





                                  share|improve this answer




























                                    1














                                    @JSideris, sample code for getting insertedId.



                                    db.collection(COLLECTION).insertOne(data, (err, result) => {
                                    if (err)
                                    return err;
                                    else
                                    return result.insertedId;
                                    });





                                    share|improve this answer


























                                      1












                                      1








                                      1







                                      @JSideris, sample code for getting insertedId.



                                      db.collection(COLLECTION).insertOne(data, (err, result) => {
                                      if (err)
                                      return err;
                                      else
                                      return result.insertedId;
                                      });





                                      share|improve this answer













                                      @JSideris, sample code for getting insertedId.



                                      db.collection(COLLECTION).insertOne(data, (err, result) => {
                                      if (err)
                                      return err;
                                      else
                                      return result.insertedId;
                                      });






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Nov 16 '18 at 8:05









                                      Pyae SonePyae Sone

                                      283313




                                      283313























                                          0














                                          if you want to take "_id" use simpley



                                          result.insertedId.toString() 


                                          // toString will convert from hex






                                          share|improve this answer




























                                            0














                                            if you want to take "_id" use simpley



                                            result.insertedId.toString() 


                                            // toString will convert from hex






                                            share|improve this answer


























                                              0












                                              0








                                              0







                                              if you want to take "_id" use simpley



                                              result.insertedId.toString() 


                                              // toString will convert from hex






                                              share|improve this answer













                                              if you want to take "_id" use simpley



                                              result.insertedId.toString() 


                                              // toString will convert from hex







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Jan 15 at 18:27









                                              dewelloperdewelloper

                                              16715




                                              16715






























                                                  draft saved

                                                  draft discarded




















































                                                  Thanks for contributing an answer to Stack Overflow!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid



                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function () {
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f14481521%2fget-the-id-of-inserted-document-in-mongo-database-in-nodejs%23new-answer', 'question_page');
                                                  }
                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  Florida Star v. B. J. F.

                                                  Error while running script in elastic search , gateway timeout

                                                  Adding quotations to stringified JSON object values