hyptos
hyptos

Reputation: 160

How to persist data after mongoose fetch?

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
             });

Upvotes: 0

Views: 266

Answers (1)

karaxuna
karaxuna

Reputation: 26930

findOne is asyncronous, so console.log is executed before findOne is finished

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);
    })

}

Do it like this:

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
         });
});

Upvotes: 1

Related Questions