public static void ChangeProxy(this HttpClientHandler handler, WebProxy newProxy)
{
if (handler.Proxy is WebProxy currentHandlerProxy)
{
currentHandlerProxy.Address = newProxy.Address;
currentHandlerProxy.Credentials = newProxy.Credentials;
}
else
{
handler.Proxy = newProxy;
}
}
Userdata集合如下:
for (var j = 0; j < u1.similar_users.length; j++) {
var pp = u1.similar_users[j];
console.log(pp);
db.collection('userdata').find({ user: pp }, { restaurants: true, _id: false }), (function(err, res) {
console.log(res);
for (var tt = 0; tt < res.length; tt++) {
console.log(res[tt]);
var u1 = res[tt];
//console.log(u1.similar_users.length);
console.log(u1.restaurants);
}
});
}
在这里,我试图找到并显示用户的resturant,并且动态传递用户的值。但是它无法访问find查询中的'pp'变量。虽然它运行良好并且在控制台中显示。如果手动传递用户var的值,例如“user:'abc'” 它工作正常,但它在循环内部不起作用。因此,查找查询后的res var也返回0作为长度,因为没有使用find()获取数据。请帮助
答案 0 :(得分:1)
在你的解决方案中,问题必须是你没有正确调用回调,试试这个:
for(var j=0;j<u1.similar_users.length;j++)
{
var pp=u1.similar_users[j];
console.log(pp); // Make sure you have the correct values
db.collection('userdata')
.find( {user:pp}, {restaurants:1,_id:0} )
.toArray((error, docs) => { // chaining toArray method!!
if (error) return process.exit(1);
console.log(docs);
// other stuff
});
}
但是当@Molda指出时,您应该在DB中委托执行所有搜索,如下所示:
var ppArray = []; // An array to store all the values you want to search
for(var j=0;j<u1.similar_users.length;j++)
pp.push(u1.similar_users[j]); // Populate the array
console.log(ppArray);
db.collection('userdata')
.find( { user: { $in : ppArray} }, {restaurants:1,_id:0} ) // Search all the documents
.toArray((error, docs) => {
if (error) return process.exit(1);
console.log(docs);
// other stuff
});
答案 1 :(得分:0)
我只是更仔细地查看了您的代码,并在此代码中注意到
...._id: false }), (function(err...
那些括号), (
不应该在那里。
此代码db.collection(..).find()
实际上与下一个函数(function(...){....})
为编写您的错误而编写的代码:
db.collection('userdata').find({ user: pp }, { restaurants: true, _id: false });
// i replaced , with ; since it has same effect here
// this is immediately invoked function expression
// which has nothing to do with the code above
// both err and res are undefined no matter what the above query returns
(function(err, res) {
console.log(res);
for (var tt = 0; tt < res.length; tt++) {
console.log(res[tt]);
var u1 = res[tt];
//console.log(u1.similar_users.length);
console.log(u1.restaurants);
}
});
这应该按预期工作
db.collection('userdata').find({ user: { $in: u1.similar_users }, { restaurants: true, _id: false }, function(err, res) {
console.log(res);
});