node.js mongodb - collection.find()。toArray(callback)返回空

时间:2013-11-23 01:25:20

标签: javascript node.js mongodb control-flow

mydocuments.find({})。toArray在我的代码中返回空。我可以看到发布了几个解决方案,但是因为我使用MongoClient.connect而没有应用它们。任何帮助将不胜感激。

var MONGOHQ_URL="mongodb://harishvc:supersecretreally@something.com:12345/abcd";
 var mongodb = require('mongodb');
 MongoClient = mongodb.MongoClient;
 var async = require('async');
 ….
  async.series([
  function (callback) {
   console.log("start: db connection");
      MongoClient.connect(MONGOHQ_URL, { server: { auto_reconnect: true } }, function(err, db2) {
         if (err) {return callback(err, "connect error");}
         db = db2;
         console.log("end: db connection");
         callback(null,"end: db connection");
     });
  },
  function (callback) {
      console.log("start: getting handle to collection");
      mydocuments = db.collection('test');  
      console.log("end: getting handle to collection");
      callback(null,"end: getting handle to collection");
  },
  function (callback) {
     console.log ("start: inserting new entries ....");
     mydocuments.insert({i:1},callback);    
     console.log ("end: inserting new entries ....");
     callback(null,"end: inserting new entries");
   },
   function (callback) {
      console.log("start: listing all entries ....");  
      mydocuments.find({}).toArray(function(err, docs) {
          if (err) {return callback(err, "connect error");}
           // Does not get executed???
            console.log("Hello World!");
      });       
      console.log("end: listing all entries ....");
      callback(null,"end: listing all entries");    
  }],
      …..

输出

start: db connection
end: db connection
start: getting handle to collection
end: getting handle to collection
start: inserting new entries ....
end: inserting new entries ....
start: listing all entries ....
end: listing all entries ....

1 个答案:

答案 0 :(得分:1)

问题出在插入数据的第3个功能中。虽然你传入了回调,但这个插入是异步的,所以它继续执行下面两行代码:

console.log ("end: inserting new entries ....");
callback(null,"end: inserting new entries");

第3个函数中的第二个callback()调用告诉async继续执行find()的第4个函数。此时,您从第3个函数插入的内容可能尚未完成。这就是为什么第四个函数中的find结果为空。

您的第3个功能应如下所示:

 function (callback) {
     console.log ("start: inserting new entries ....");
     mydocuments.insert({i:1},function(err) {
         if (err) {
             callback(err, "error inserting");
         } else {
             callback(null,"end: inserting new entries");
         }
         console.log ("end: inserting new entries ....");

     });    
 },

这可以保证第3个函数中的插入在进入下一个执行find()的函数(4th)之前完成。