Node.js:异步嵌套回调在for循环的每个迭代中都不起作用
Node.js: Asynchronous nested callback not working within each iteration in a for loop
我使用了以下代码片段来获取存储在mongodb 中的特定用户的追随者
保存的用户json如下
{ "_id":{
"$oid":"5440f606255cd4740e88ed21" }, "username":"test2", "email":"test2%40gmail.com", "name":"Test2", "version":null, "password":"2ea01e7a318f15378641f47469613ce6817cc91a", "gender":null, "dob":null, "profile_image":"1413543430090.jpg", "status":"1", "role_id":"2", "posts":[
], "followers":[
{
"_id":{
"$oid":"5440fb8fad74e87c0fdf22e5"
},
"user_id":"5440f0c3ae7a24ac0e47ca9e",
"unfollow":"0",
"created":{
"$date":"2014-10-17T11:20:47.107Z"
}
},
{
"_id":{
"$oid":"5440fc1e51a684e00b72db8a"
},
"user_id":"5440f9790dd5d4a40b6cec18",
"unfollow":0,
"created":{
"$date":"2014-10-17T11:23:10.645Z"
}
} ] }
为了获得用户的所有追随者,我使用了以下代码片段。在这个代码中,追随者使用foreach循环。
主要问题是foreach循环中的find查询由于异步回调函数而不起作用
db.collection('users').findOne({'_id': new mongo.ObjectID('5440f606255cd4740e88ed21'), "followers.unfollow": '0'}, {followers: 1, _id: 1}, function(err, user) {
var followers = user.followers;
var finalarray = [];
followers.forEach(function(follower, index) {
db.collection('users').find({"user._id": new mongo.ObjectID(follower._id)}, {_id: 1, username: 1, profile_picture: 1},function(err, users) {
if (user) {
var temp_follower = [];
temp_follower = {'follower_id': user._id, 'username': user.username,'profile_picture': user.profile_picture};
finalarray.push(temp_follower);
}
});
});
});
res.json({'replyCode': "success", 'replyMsg': "followers get successfully", 'followers': finalarray});
最后,作为JSON的回应,我没有找到任何追随者的用户详细信息
帮我解决这个问题。
感谢
Dinesh Prajapati
您可以使用$in运算符而不是循环。以下是的示例代码框架
db.collection('users').findOne({'_id': new mongo.ObjectID('5440f606255cd4740e88ed21'), "followers.unfollow": '0'}, {followers: 1, _id: 1}, function(err, user) {
db.collection('users').find({"user._id":{$in: user.followers }, {_id: 1, username: 1, profile_picture: 1},function(err, users) {
res.json({'replyCode': "success", 'replyMsg': "followers get successfully", 'followers': users});
}
});
});
请注意,要执行类似sql联接的操作,您可能必须使用mapReduce之类的东西。您可以参考此链接。
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 监视函数从服务返回不起作用,但作用域函数起作用
- 幻灯片滚动javascript不起作用
- 简单的javascript在Shopify中不起作用
- Recaptcha在IE7和IE8中不起作用
- Ember Data DS.Model's set函数不起作用
- JsFiddle上的鼠标事件不起作用
- 我的AngularJS表达式没有'不起作用
- 点击按钮输入不起作用
- 面向对象的Javascript代码在IE7中不起作用
- 分部隐藏在jquery中不起作用
- 在phonegap应用程序内部重定向不起作用
- 在 jQuery 不起作用的情况下迭代变量
- 对象数组的迭代不起作用
- 莫代尔没有'我的代码不起作用
- Node.js:异步嵌套回调在for循环的每个迭代中都不起作用
- jQuery - 如何滚动浏览子类 addclass 然后在一次迭代中删除类 setTimout 不起作用
- 迭代对象和更改get-request对象的值不起作用
- 代码在jsfiddle中工作,但当我将所有代码放入我的网站时就不起作用了
- 推特预先输入的bloodhound代币不起作用