【问题标题】:How to persist data after mongoose fetch?mongoose fetch 后如何持久化数据?
【发布时间】:2013-06-29 18:02:21
【问题描述】:

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

【问题讨论】:

    标签: javascript node.js mongoose


    【解决方案1】:

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

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

    【讨论】:

    • 不,我需要函数 findOne 之外的 totalSize 并使用 game.size 进行更新。你只是把它移了进去,这不是我想要的。
    • 查看我的编辑我只需要为我的 res.render 更新 totalSize 我不知道你是否看到我正在尝试做的事情:/顺便感谢你的时间 :)
    • @hyptos 我再次编辑 :) 你应该了解更多关于异步函数的信息:stackoverflow.com/questions/6898779/…
    • 感谢第一次使用 nodejs mongo 和他们的朋友,我会查看你告诉我的帖子!
    猜你喜欢
    • 2017-04-29
    • 2017-01-01
    • 1970-01-01
    • 2017-10-13
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    相关资源
    最近更新 更多