2016-04-21 114 views
0

我對nodejs有點新。我正在構建一個類似Facebook的應用程序。無論如何,我正在查詢代碼中顯示的數據庫。但前端記錄I console.log的順序混亂而且不合適,每次都不一樣。你能告訴我我錯在哪裏嗎?數據的順序不正確nodejs

router.get('/home', isAuthenticated, function(req, res){ 
    var friendsIds = req.user.friends; 
    friendsIds.push(req.user.id); 
    var cbdone = 0; 

    Status.find({statuserId : {$in: friendsIds}}, null, {skip : 0, limit: 5, sort: {_id: -1}}, function(err, statuses) { 

     for (var i = 0; i < statuses.length; i++) { 
      (function(currStatus){ 
       var currentStatus = currStatus; 
       var a = currentStatus._id.getTimestamp(); 
       if(currentStatus.likedBy){ 
        if (currentStatus.likedBy.indexOf(req.user.id) > -1) { 
         currentStatus.isLiked = true; 
        }; 
        currentStatus.likersCount = currentStatus.likedBy.length; 
       } else { 
        currentStatus.isLiked = false; 
        currentStatus.likersCount = 0; 
       } 

       Comment.find({statusId : currentStatus.id}, null, {sort: {_id: -1}}, function(err, comments){ 
        for (var i = comments.length - 1; i >= 0; i--) { 
         comments[i].likersCount = comments[i].likedBy.length; 
         comments[i].isLiked = comments[i].likedBy.indexOf(req.user.id) > -1; 
        }; 
        currentStatus.comments = comments; 
        cbdone++; 
        if(cbdone === statuses.length){ 
         res.render('home2', { 
          user: req.user, 
          statuses: statuses 
         }); 
        } 
       }); 

      })(statuses[i]);    
     }; 
    }); 
}); 
+0

我看到的是一些錯誤的模式設計,你不應該有註釋集合,你應該將註釋作爲一個數組嵌入到狀態集合中,這樣你將減少請求的數量數據庫劇烈 –

+0

但是一行mongodb文檔有一些大小限制,評論可以不斷增長。我有道理嗎? –

+0

是的,文檔的閾值大小是16mb,你應該得到很多評論來做它,任何方式你會註冊在網格中的圖像,你的文件很少會超過MB –

回答

0

您應該使用Promise.all或Promise + co或async/await按順序進行異步調用的結果。

Status.find({statuserId : {$in: friendsIds}}, null, {skip : 0, limit: 5, sort: {_id: -1}}, function (err, statuses) { 
    co(function *() { 
    const Comments = yield statuses.map(function (currentStatus) { 
     var currentStatus = currStatus; 
     var a = currentStatus._id.getTimestamp(); 
     if(currentStatus.likedBy){ 
     if (currentStatus.likedBy.indexOf(req.user.id) > -1) { 
      currentStatus.isLiked = true; 
     }; 
     currentStatus.likersCount = currentStatus.likedBy.length; 
     } else { 
     currentStatus.isLiked = false; 
     currentStatus.likersCount = 0; 
     } 
     return new Promise(function (resolve, reject) { 
     Comment.find({statusId : currentStatus.id}, null, {sort: {_id: -1}}, function(err, comments){ 
      if(err) return reject(err); 
      for (var i = comments.length - 1; i >= 0; i--) { 
      comments[i].likersCount = comments[i].likedBy.length; 
      comments[i].isLiked = comments[i].likedBy.indexOf(req.user.id) > -1; 
      }; 
      resolve(comments); 
     }); 
     }) 
    }); 
...... 
    res.render('home2', { 
     user: req.user, 
     statuses: statuses 
    }); 
    }) 

});