How to get a callback on MongoDB collection.find()












42














When I run collection.find() in MongoDB/Node/Express, I'd like to get a callback when it's finished. What's the correct syntax for this?



 function (id,callback) {

var o_id = new BSON.ObjectID(id);

db.open(function(err,db){
db.collection('users',function(err,collection){
collection.find({'_id':o_id},function(err,results){ //What's the correct callback synatax here?
db.close();
callback(results);
}) //find
}) //collection
}); //open
}









share|improve this question





























    42














    When I run collection.find() in MongoDB/Node/Express, I'd like to get a callback when it's finished. What's the correct syntax for this?



     function (id,callback) {

    var o_id = new BSON.ObjectID(id);

    db.open(function(err,db){
    db.collection('users',function(err,collection){
    collection.find({'_id':o_id},function(err,results){ //What's the correct callback synatax here?
    db.close();
    callback(results);
    }) //find
    }) //collection
    }); //open
    }









    share|improve this question



























      42












      42








      42


      10





      When I run collection.find() in MongoDB/Node/Express, I'd like to get a callback when it's finished. What's the correct syntax for this?



       function (id,callback) {

      var o_id = new BSON.ObjectID(id);

      db.open(function(err,db){
      db.collection('users',function(err,collection){
      collection.find({'_id':o_id},function(err,results){ //What's the correct callback synatax here?
      db.close();
      callback(results);
      }) //find
      }) //collection
      }); //open
      }









      share|improve this question















      When I run collection.find() in MongoDB/Node/Express, I'd like to get a callback when it's finished. What's the correct syntax for this?



       function (id,callback) {

      var o_id = new BSON.ObjectID(id);

      db.open(function(err,db){
      db.collection('users',function(err,collection){
      collection.find({'_id':o_id},function(err,results){ //What's the correct callback synatax here?
      db.close();
      callback(results);
      }) //find
      }) //collection
      }); //open
      }






      node.js mongodb express






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 26 '12 at 16:09









      JohnnyHK

      205k37433362




      205k37433362










      asked Jul 26 '12 at 2:40









      John

      1,81762641




      1,81762641
























          2 Answers
          2






          active

          oldest

          votes


















          40














          That's the correct callback syntax, but what find provides to the callback is a Cursor, not an array of documents. So if you want your callback to provide results as an array of documents, call toArray on the cursor to return them:



          collection.find({'_id':o_id}, function(err, cursor){
          cursor.toArray(callback);
          db.close();
          });


          Note that your function's callback still needs to provide an err parameter so that the caller knows whether the query worked or not.



          2.x Driver Update



          find now returns the cursor rather than providing it via a callback, so the typical usage can be simplified to:



          collection.find({'_id': o_id}).toArray(function(err, results) {...});


          Or in this case where a single document is expected, it's simpler to use findOne:



          collection.findOne({'_id': o_id}, function(err, result) {...});





          share|improve this answer























          • So in this case where I'm only returning one result, it's normal to reference data[0] in the controller?
            – John
            Jul 26 '12 at 3:13






          • 2




            In that case you'd want to use findOne instead, which directly provides the document to the callback. See mongodb.github.com/node-mongodb-native/api-generated/…
            – JohnnyHK
            Jul 26 '12 at 3:15



















          21














          Based on JohnnyHK answer I simply wrapped my calls inside db.open() method and it worked. Thanks @JohnnyHK.



          app.get('/answers', function (req, res){
          db.open(function(err,db){ // <------everything wrapped inside this function
          db.collection('answer', function(err, collection) {
          collection.find().toArray(function(err, items) {
          console.log(items);
          res.send(items);
          });
          });
          });
          });


          Hope it is helpful as an example.






          share|improve this answer























          • @John Thanks for formatting the code. I just missed them :)
            – Anmol Saraf
            Apr 30 '13 at 10:08






          • 12




            And they call it... callback hell! It begins...
            – Karl Morrison
            Mar 30 '15 at 0:45






          • 1




            i love you - - -
            – timbo7io
            Oct 6 '17 at 5:38










          • I am using same but I got db.open is not function error can you help me
            – Pramod
            Oct 10 at 8:02











          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%2f11661545%2fhow-to-get-a-callback-on-mongodb-collection-find%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          40














          That's the correct callback syntax, but what find provides to the callback is a Cursor, not an array of documents. So if you want your callback to provide results as an array of documents, call toArray on the cursor to return them:



          collection.find({'_id':o_id}, function(err, cursor){
          cursor.toArray(callback);
          db.close();
          });


          Note that your function's callback still needs to provide an err parameter so that the caller knows whether the query worked or not.



          2.x Driver Update



          find now returns the cursor rather than providing it via a callback, so the typical usage can be simplified to:



          collection.find({'_id': o_id}).toArray(function(err, results) {...});


          Or in this case where a single document is expected, it's simpler to use findOne:



          collection.findOne({'_id': o_id}, function(err, result) {...});





          share|improve this answer























          • So in this case where I'm only returning one result, it's normal to reference data[0] in the controller?
            – John
            Jul 26 '12 at 3:13






          • 2




            In that case you'd want to use findOne instead, which directly provides the document to the callback. See mongodb.github.com/node-mongodb-native/api-generated/…
            – JohnnyHK
            Jul 26 '12 at 3:15
















          40














          That's the correct callback syntax, but what find provides to the callback is a Cursor, not an array of documents. So if you want your callback to provide results as an array of documents, call toArray on the cursor to return them:



          collection.find({'_id':o_id}, function(err, cursor){
          cursor.toArray(callback);
          db.close();
          });


          Note that your function's callback still needs to provide an err parameter so that the caller knows whether the query worked or not.



          2.x Driver Update



          find now returns the cursor rather than providing it via a callback, so the typical usage can be simplified to:



          collection.find({'_id': o_id}).toArray(function(err, results) {...});


          Or in this case where a single document is expected, it's simpler to use findOne:



          collection.findOne({'_id': o_id}, function(err, result) {...});





          share|improve this answer























          • So in this case where I'm only returning one result, it's normal to reference data[0] in the controller?
            – John
            Jul 26 '12 at 3:13






          • 2




            In that case you'd want to use findOne instead, which directly provides the document to the callback. See mongodb.github.com/node-mongodb-native/api-generated/…
            – JohnnyHK
            Jul 26 '12 at 3:15














          40












          40








          40






          That's the correct callback syntax, but what find provides to the callback is a Cursor, not an array of documents. So if you want your callback to provide results as an array of documents, call toArray on the cursor to return them:



          collection.find({'_id':o_id}, function(err, cursor){
          cursor.toArray(callback);
          db.close();
          });


          Note that your function's callback still needs to provide an err parameter so that the caller knows whether the query worked or not.



          2.x Driver Update



          find now returns the cursor rather than providing it via a callback, so the typical usage can be simplified to:



          collection.find({'_id': o_id}).toArray(function(err, results) {...});


          Or in this case where a single document is expected, it's simpler to use findOne:



          collection.findOne({'_id': o_id}, function(err, result) {...});





          share|improve this answer














          That's the correct callback syntax, but what find provides to the callback is a Cursor, not an array of documents. So if you want your callback to provide results as an array of documents, call toArray on the cursor to return them:



          collection.find({'_id':o_id}, function(err, cursor){
          cursor.toArray(callback);
          db.close();
          });


          Note that your function's callback still needs to provide an err parameter so that the caller knows whether the query worked or not.



          2.x Driver Update



          find now returns the cursor rather than providing it via a callback, so the typical usage can be simplified to:



          collection.find({'_id': o_id}).toArray(function(err, results) {...});


          Or in this case where a single document is expected, it's simpler to use findOne:



          collection.findOne({'_id': o_id}, function(err, result) {...});






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 2 '17 at 13:43

























          answered Jul 26 '12 at 3:09









          JohnnyHK

          205k37433362




          205k37433362












          • So in this case where I'm only returning one result, it's normal to reference data[0] in the controller?
            – John
            Jul 26 '12 at 3:13






          • 2




            In that case you'd want to use findOne instead, which directly provides the document to the callback. See mongodb.github.com/node-mongodb-native/api-generated/…
            – JohnnyHK
            Jul 26 '12 at 3:15


















          • So in this case where I'm only returning one result, it's normal to reference data[0] in the controller?
            – John
            Jul 26 '12 at 3:13






          • 2




            In that case you'd want to use findOne instead, which directly provides the document to the callback. See mongodb.github.com/node-mongodb-native/api-generated/…
            – JohnnyHK
            Jul 26 '12 at 3:15
















          So in this case where I'm only returning one result, it's normal to reference data[0] in the controller?
          – John
          Jul 26 '12 at 3:13




          So in this case where I'm only returning one result, it's normal to reference data[0] in the controller?
          – John
          Jul 26 '12 at 3:13




          2




          2




          In that case you'd want to use findOne instead, which directly provides the document to the callback. See mongodb.github.com/node-mongodb-native/api-generated/…
          – JohnnyHK
          Jul 26 '12 at 3:15




          In that case you'd want to use findOne instead, which directly provides the document to the callback. See mongodb.github.com/node-mongodb-native/api-generated/…
          – JohnnyHK
          Jul 26 '12 at 3:15













          21














          Based on JohnnyHK answer I simply wrapped my calls inside db.open() method and it worked. Thanks @JohnnyHK.



          app.get('/answers', function (req, res){
          db.open(function(err,db){ // <------everything wrapped inside this function
          db.collection('answer', function(err, collection) {
          collection.find().toArray(function(err, items) {
          console.log(items);
          res.send(items);
          });
          });
          });
          });


          Hope it is helpful as an example.






          share|improve this answer























          • @John Thanks for formatting the code. I just missed them :)
            – Anmol Saraf
            Apr 30 '13 at 10:08






          • 12




            And they call it... callback hell! It begins...
            – Karl Morrison
            Mar 30 '15 at 0:45






          • 1




            i love you - - -
            – timbo7io
            Oct 6 '17 at 5:38










          • I am using same but I got db.open is not function error can you help me
            – Pramod
            Oct 10 at 8:02
















          21














          Based on JohnnyHK answer I simply wrapped my calls inside db.open() method and it worked. Thanks @JohnnyHK.



          app.get('/answers', function (req, res){
          db.open(function(err,db){ // <------everything wrapped inside this function
          db.collection('answer', function(err, collection) {
          collection.find().toArray(function(err, items) {
          console.log(items);
          res.send(items);
          });
          });
          });
          });


          Hope it is helpful as an example.






          share|improve this answer























          • @John Thanks for formatting the code. I just missed them :)
            – Anmol Saraf
            Apr 30 '13 at 10:08






          • 12




            And they call it... callback hell! It begins...
            – Karl Morrison
            Mar 30 '15 at 0:45






          • 1




            i love you - - -
            – timbo7io
            Oct 6 '17 at 5:38










          • I am using same but I got db.open is not function error can you help me
            – Pramod
            Oct 10 at 8:02














          21












          21








          21






          Based on JohnnyHK answer I simply wrapped my calls inside db.open() method and it worked. Thanks @JohnnyHK.



          app.get('/answers', function (req, res){
          db.open(function(err,db){ // <------everything wrapped inside this function
          db.collection('answer', function(err, collection) {
          collection.find().toArray(function(err, items) {
          console.log(items);
          res.send(items);
          });
          });
          });
          });


          Hope it is helpful as an example.






          share|improve this answer














          Based on JohnnyHK answer I simply wrapped my calls inside db.open() method and it worked. Thanks @JohnnyHK.



          app.get('/answers', function (req, res){
          db.open(function(err,db){ // <------everything wrapped inside this function
          db.collection('answer', function(err, collection) {
          collection.find().toArray(function(err, items) {
          console.log(items);
          res.send(items);
          });
          });
          });
          });


          Hope it is helpful as an example.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Apr 30 '13 at 0:50









          John

          1,81762641




          1,81762641










          answered Apr 26 '13 at 15:58









          Anmol Saraf

          9,16974052




          9,16974052












          • @John Thanks for formatting the code. I just missed them :)
            – Anmol Saraf
            Apr 30 '13 at 10:08






          • 12




            And they call it... callback hell! It begins...
            – Karl Morrison
            Mar 30 '15 at 0:45






          • 1




            i love you - - -
            – timbo7io
            Oct 6 '17 at 5:38










          • I am using same but I got db.open is not function error can you help me
            – Pramod
            Oct 10 at 8:02


















          • @John Thanks for formatting the code. I just missed them :)
            – Anmol Saraf
            Apr 30 '13 at 10:08






          • 12




            And they call it... callback hell! It begins...
            – Karl Morrison
            Mar 30 '15 at 0:45






          • 1




            i love you - - -
            – timbo7io
            Oct 6 '17 at 5:38










          • I am using same but I got db.open is not function error can you help me
            – Pramod
            Oct 10 at 8:02
















          @John Thanks for formatting the code. I just missed them :)
          – Anmol Saraf
          Apr 30 '13 at 10:08




          @John Thanks for formatting the code. I just missed them :)
          – Anmol Saraf
          Apr 30 '13 at 10:08




          12




          12




          And they call it... callback hell! It begins...
          – Karl Morrison
          Mar 30 '15 at 0:45




          And they call it... callback hell! It begins...
          – Karl Morrison
          Mar 30 '15 at 0:45




          1




          1




          i love you - - -
          – timbo7io
          Oct 6 '17 at 5:38




          i love you - - -
          – timbo7io
          Oct 6 '17 at 5:38












          I am using same but I got db.open is not function error can you help me
          – Pramod
          Oct 10 at 8:02




          I am using same but I got db.open is not function error can you help me
          – Pramod
          Oct 10 at 8:02


















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f11661545%2fhow-to-get-a-callback-on-mongodb-collection-find%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

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          Refactoring coordinates for Minecraft Pi buildings written in Python