[
{
"_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"
}
]
I have a collection of users. One of the user is shown in the code above. I want to select one user by its id. Then FROM THE SELECTED USER I want objects from the stats array which have type: "three". I have looked for quite some time and havent found a solution. The current method I am using is this:
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);
}
});
The problem is that the stats array will get too large and the process will be very slow.
If you cannot find a way to select from the stats array in the query, I'd say at least do not use splice to filter out stats of the wrong type. Try using filter, or pushing stats of type 'three' into a new array to see if the performance improves.