我正在对 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
             });