如何在猫鼬获取后持久化数据

How to persist data after mongoose fetch?

本文关键字:持久化 数据 获取      更新时间:2023-09-26

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

findOne是异步的,因此console.log在findOne完成之前执行

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;
        }
        console.log(totalSize);
    })
}

这样做:

function findTotalSize(callback){
    var totalSize = 0;
    var gameLength = json[0].game.length;
    for (var i = gameLength - 1; i >= 0; i--) {
        Game.findOne({
            'steamID': json[0].game[i].appID[0]
        }, function (err, game) {
            if (err) return handleError(err);
            if (game) {
               totalSize += game.size;
            }
            if(--gameLength == 0)
               callback(totalSize);
        })
    }
}
//use it
findTotalSize(function(totalSize){
    res.render('user', {
             steamid: steamID,
             steamid64: steamID64,
             size: totalSize,
             content: json
         });
});