簡體   English   中英

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循環中的查找查詢無法正常工作

  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-join的操作,您可能必須使用mapReduce之類的東西。 您可以參考此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM