2017-04-26 110 views
0
[ 
    { 
     "_id": "59009087f8ed4e2ecc91fcbe", 
     "password": "test", 
     "email": "", 
     "username": "root", 
     "__v": 3, 
     "stats": [ 
      { 
       "_id": "590090a0f8ed4e2ecc91fcbf", 
       "time": 98, 
       "scramble": "U2 F R U' R B' L' U L' B2 R2 B F' U2 R' B2 R2 D R2 U", 
       "type": "three", 
       "status": 0, 
       "date": "2017-04-26T12:20:48.622Z" 
      }, 
      { 
       "_id": "590090adf8ed4e2ecc91fcc0", 
       "time": 120, 
       "scramble": "R2 U2 D' U' B D B L' U2 R2 F2 L2 R' F2 U F2 L2 D L2", 
       "type": "three", 
       "status": 0, 
       "date": "2017-04-26T12:21:01.318Z" 
      }, 
      { 
       "_id": "590090da8f0e120320f36945", 
       "time": 191, 
       "scramble": "F2 B' L F R B' F B' D' F2 R2 B U' D' F U D B' F' D", 
       "type": "four", 
       "status": 0, 
       "date": "2017-04-26T12:21:46.679Z" 
      } 
     ], 
     "accountDate": "2017-04-26T12:20:23.085Z" 
    } 
] 

我有一個用戶的集合。其中一位用戶在上面的代碼中顯示。我想通過它的ID選擇一個用戶。然後從選擇的用戶我想要stats數組中有類型爲「三」的對象。我已經尋找了相當一段時間,沒有找到解決辦法。我正在使用的當前方法是這樣的:模型內查詢模型

User.findOne({ 
     _id: id 
    }, function (err, user) { 
     if(err){ 
      console.log(err); 
     } else { 
      user.stats.forEach(function (time, i, array) { 
       if(time.type != req.body.type){ 
        array.splice(i, 1); 
       } 
      }); 
      res.send(user.stats); 
     } 

}); 

問題是stats數組將變得太大,並且進程會非常緩慢。

回答

0

如果你找不到從查詢中的統計數組中選擇的方法,我會說至少不要使用splice來過濾錯誤類型的統計信息。嘗試使用過濾器,或將'3'類型的統計信息推入新陣列,以查看性能是否提高。

https://jsperf.com/splice-vs-filter

+0

我做到了。我的TTFB大約是250ms。這很好嗎?有時候它會跳到2秒。 – mrf1freak