0
我用下面的代码片段来获得其存储在MongoDB中的Node.js:异步回调嵌套不每次迭代中工作的for循环
保存的用户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循环内找到查询不是因为异步回调函数的响应JSON工作
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});
最后我还没有找到任何跟随用户详细
帮我摆脱这个问题。
感谢
迪内希生主
'find({“user._id”:'好像是我的错字,我想你的第二个请求不会因为这个返回任何东西。 – 2014-10-22 07:04:54