【发布时间】:2017-07-25 17:56:26
【问题描述】:
我正在使用 Nodejs、MongoDB 和 Express 进行编码。下面的代码在 MongoDB 中查找具有特定 id 的用户对象。一旦找到用户对象,它就会检索该对象的收藏属性。最喜欢的属性是一个数组,它的每个元素都是一个产品的_id。我试图遍历这个数组。对于每个循环,我尝试从 MongoDB 检索产品对象并将该产品对象附加到新数组(在我下面的代码中,它称为“列表”)。我放了一些 console.log() 来检查列表的值。它对每个循环都有价值,但最后当我得到最后一个时,它是空的。我知道问题的发生是因为我没有正确使用 deferred.resolve 和 deferred.promise。请帮助我并解释 deferred.resolve 和 deferred.promise 在代码中的作用。非常感谢
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函数中请求的任何回调之前解决了延迟。回调将产品推送到list,但这是一段时间后,在您登录列表并发现它为空之后。 -
我不知道您使用哪个库与 MongoDB 进行交互,但如果您使用的是 Mongoose(看起来不太像),您应该真正研究一下 Query Population。查看文档:mongoosejs.com/docs/populate.html
-
@SilvestreHerrera,我不使用猫鼬。我以前用过。这很棒。这一次,我只想尝试使用 MongoDB。
-
@Traktor53。谢谢你。它是异步的。我还是不太明白。你认为这是因为异步问题还是关闭问题?
标签: javascript jquery arrays node.js mongodb