2015-07-10 67 views
0

我在嘗試將返回數據保存到父範圍時遇到了一些範圍問題。這裏是我的來源,任何幫助將不勝感激。我不能爲我的生活得到表格=數據。NodeJS無法訪問子對象中的對象範圍

我的數據var console.logs正確地只是一個範圍問題。

function OpenDB(mongoUrl, callBack){ 
    var MongoClient = mongodb.MongoClient; 
    var url = mongoUrl || "mongodb://" + process.env.IP + "/test"; 
    MongoClient.connect(url, function(err, db) { 
     if(err){ 
      console.log(err); 
     } 
     console.log(" Connected correctly to server "); 
     callBack(db, function(){ 
      console.log(" Disconnected from server "); 
      db.close(); 
     }); 
    }.bind(this)); 
} 
var GetTableAsArray = function(tableName){ 
    var table = []; 
    OpenDB(null, function(db,cb){ 
     db.collection(tableName).find().toArray(function(err, data){ 
      if(err){ 
       console.log(err); 
      } 
      //this is the problem 
      table = data; 
      cb(); 
     }); 
    }); 
    return table; 
}; 

回答

1

通過時間GetTablesAsArray函數返回,table仍然只是一個空數組。這裏的問題在於你的查詢是以異步的方式發生的,這意味着你的代碼不會在繼續之前等待它完成。您可以使用回調來執行您想要的任何代碼,只要它被提取即可。

var GetTableAsArray = function(tableName, callback){ 
    OpenDB(null, function(db,cb){ 
     db.collection(tableName).find().toArray(function(err, data){ 
      if(err){ 
       console.log(err); 
      } 
      //this is the problem 
      table = data; 
      cb(); 
      callback (data); 
     }); 
    }); 
}; 

GetTableAsArray('tableName', function (table) { 
    console.log(table); 
}); 
+0

它的工作,謝謝! –