I am doing a request on a mongoDB and I would like to increment a variable for each object I found in my database.
My problem is that my variable totalSize seems to not persist the data it gets, I don't know why :/
I believed it was a closure problem in js but someone told me to see if it's not the asynchronous trait of query object that cause my problem.
I'm lost :/
var totalSize = 0;
for (var i = json[0].game.length - 1; i >= 0; i--) {
//When I found a game, I would like to increment his size in totalSize
Game.findOne({
'steamID': json[0].game[i].appID[0]
}, function (err, game) {
if (err) return handleError(err);
if (game) {
//everything is fine here totalSize is the right number
totalSize += game.size;
}
})// where he "forget" my var
//totalSize is still at 0 like I never incremented the variable
console.log(totalSize);
}
res.render('user', {
steamid: steamID,
steamid64: steamID64,
size: totalSize,
content: json
});