mongoDB でリクエストを行っており、データベースで見つかった各オブジェクトの変数をインクリメントしたいと考えています。
私の問題は、変数 totalSize が取得したデータを保持していないように見えることです。理由はわかりません:/
私はそれが js のクロージャーの問題だと信じていましたが、私の問題の原因がクエリ オブジェクトの非同期特性ではないかどうかを確認するように誰かに言われました。
道に迷いました :/
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
});