我无法从嵌套查询中获得结果,loc始终为空。当我打印查询参数时,它的值是正确的,并且数据库集合'users‘包含来自数组friendsP的ids为的文档。
var acquireFriendsPositions = function(db, id, res, callback) {
var cursor = db.collection('users').find({"_id" : new ObjectId(id)}, {_id:0, friends:1});
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
friendsP = doc.friends;
console.log(friendsP); //I get the array friendsP
for(var i =0; i<friendsP.length; i++)
{
console.log(friendsP[i]); //friendsP[i] has proper value
var curs = db.collection('users').find({"_id" : new ObjectId(friendsP[i])}); //but query returns null
curs.each(function(err, loc) {
//assert.equal(err, null);
if(loc!= null) {
console.log(loc);
friendsPos.push(loc);
}
else {
console.log("else");
}
});
}
promise(friendsPos, res); //here i wait for friendsPos and use it in res.send(), but friendsPos is empty because loc is always null
} else {
callback(); //callback does db.close();
}
});
};发布于 2016-06-23 05:08:02
如果这就是您正在使用的代码,我怀疑friendsP值会在下一个each周期中被提升和覆盖。这意味着您应该能够通过简单地将代码更改为var friendsP = doc.friends来修复这个问题,这样friendsP变量就在function范围内。如果这是正在发生的事情,这是一个令人讨厌的bug,您应该始终使用局部作用域声明变量,以防止这种情况发生。
发布于 2016-06-23 13:10:52
尝试将其用于强制转换对象Id:
var mongodb = require('mongodb');
mongodb.ObjectID.createFromHexString(friendsP[i]);发布于 2016-06-23 21:45:16
谢谢你们。实际上,问题出在callback(),它在查询执行之前关闭了连接。这是我的新代码:
var acquireFriendsPositions = function(db, id, res, callback) {
db.collection('users').findOne({"_id" : new ObjectId(id)},
function(err, item) {
var friendsP = item.friends;
var locFriends = [];
promise(locFriends, res);
var x = 0;
for(i =0; i<friendsP.length; i++)
{
db.collection('users').findOne({"_id" : friendsP[i]}, function(err,subItem){
x=x+1;
//console.log(subItem);
locFriends.push(subItem);
if(x==friendsP.length)
callback();
});
}
});
};https://stackoverflow.com/questions/37978001
复制相似问题