2017-04-06 46 views
0

我的問題似乎與節點的異步方面有關,但我無法理解爲什麼。Node + Mongo:findOne OK但find()。forEach DONT

此代碼的工作:

 expertsArray = ["expert1", "expert2"]; 
     db.collection("users").findOne({first_name: expertsArray[0]}, function(err, expert) { 
     console.log(expert.userid); 
     }); 
     }); 

該代碼中的錯誤:

 expertsArray = ["expert1", "expert2"]; 
     db.collection("users").find({ first_name: {$in: expertsArray} }, function(err, experts) { 
     experts.forEach(function(err, expert) { 
      console.log(expert.userid); 
      }); 
     }); 
     }); 

在第二種情況下,專家存在並且是一個[對象物體],但誤差:

error: [FATAL] An unhandled exception occured in your bot TypeError: Cannot read property 'userid' of null

我也嘗試把第一個代碼放到FOR循環中,但是出現同樣的錯誤... 任何人都可以幫助我理解?非常感謝:)

+0

怎麼會是對象和空的同時......也許這是一個薛定諤變量。 – DanFromGermany

+0

對不起,錯字:專家存在,但專家不 –

回答

2

您的forEach中的參數是錯誤的。

Mozilla,參數是:

currentValue, index 

但是你必須

err, expert 

所以會轉而:

experts.forEach(function(expert, expertIndex) { 
    console.log(expert.userid); 
    }); 
}); 
+0

你是最棒的! ;)非常感謝你 –

+0

我應該與each()函數混合起來:cursor.each(function(err,item){ –

相關問題