2014-10-22 106 views
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}); 

最後我還沒有找到任何跟隨用戶詳細

幫我擺脫這個問題。

感謝

迪內希生主

+0

'find({「user._id」:'好像是我的錯字,我想你的第二個請求不會因爲這個返回任何東西。 – 2014-10-22 07:04:54

回答

0

可以在運營商,而不是循環使用$。下面是一個示例代碼框架

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之類的話。你可以參考這個link