我使用Nodejs,MongoDB和Express编码。下面的代码在MongoDB中查找具有特定ID的用户对象。一旦找到用户对象,它将检索该对象的收藏属性。 favorite属性是一个数组,其每个元素都是产品的_id。我试图循环这个数组。在每个循环中,我尝试从MongoDB中检索一个产品对象,并将此产品对象附加到新数组(在我的代码中称为“list”)。我把一些console.log()来检查列表的值。它对每个循环都有价值,但最终当我得到最后一个循环时,它是空的。我知道问题发生,因为我没有正确使用deferred.resolve和deferred.promise。请帮我解释代码中的deferred.resolve和deferred.promise作品。非常感谢您Arrayj在Nodejs和MongoDB中使用forEach循环返回null值
function showBasket(user) {
var deferred = Q.defer();
var list =[];
db.users.findById(user, function (err, user) {
if (err) deferred.reject(err);
if (user) {
var favorite = user.favorite;
favorite.forEach(function(e){
db.products.findById(mongo.helper.toObjectID(e), function(err, product){
if (err) deferred.reject(err);
if (product) {
list.push(product);
console.log(list);// list has value here
}
})//end db.products.findById
})//end of forEach
} //end of if
console.log(list);// But finally, list has null value here
deferred.resolve(list);
});//end of db.users.findById
return deferred.promise;
}
是'db.products.findById'异步?如果是这样,'list'正在测试中,并且在'.forEach'函数中请求的任何回调之前解析延迟。回调会将产品推到“列表”上,但这是一段时间之后,在您登录列表后发现它为空。 – traktor53
我不知道你使用哪个库来与MongoDB进行交互,但是如果你使用的是Mongoose(它看起来不太像),你应该看看Query Population。看看文档:http://mongoosejs.com/docs/populate.html –
@SilvestreHerrera,我不使用猫鼬。我之前使用过它。这很棒。这一次,我只想尝试使用MongoDB。 – sonle