【问题标题】:Node.js Mongoose callbackNode.js Mongoose 回调
【发布时间】:2014-11-19 05:10:44
【问题描述】:

我看到了很多答案,但我仍然无法完成这项工作。 我有一个简单的函数,我想返回在 Mongoose 上找到的查询的长度。 它是这样的:

app.use(function(req, res, next) {
        res.locals.user = null
        if (req.isAuthenticated()) {
            res.locals.user = req.user;
            getMt(req.user.id, function(val) {
                console.log(val) // == 5
                res.locals.mt = val;
            });
        }
        console.log(res.locals.mt); // == undefined
....
}
function getMt(user_id, callback) {
    var Model = require('./models/mt');
    Model.find({'users.user_id': user_id}, 'token', function(err, list) {
        if (err)
            callback(0);
        if (!list)
            callback(0);
        if (list)
            callback(list.length);
    });
}

我阅读了很多关于异步的内容,但我仍然找不到解决方案。 res.locals.mt 在回调中的 res.locals.mt = val 之后仍然显示 undefined。

有人能指出我正确的方向吗? 提前致谢。

【问题讨论】:

  • 具体是什么问题,请定义。
  • 听起来像是.count()的案例?
  • 除了使用 count(),Model.find() 调用中的第二项应该是一个对象。试试这个查询:Model.find({some:'query'},{token:true},function(err, list){})

标签: node.js asynchronous express callback mongoose


【解决方案1】:

调用next函数!

app.use(function(req, res, next) {
        res.locals.user = null
        if (req.isAuthenticated()) {
            res.locals.user = req.user;
            getMt(req.user.id, function(val) {
                console.log(val) // == 5
                res.locals.mt = val;
                next(); //<---- add this!!!
            });
        }
....
}

【讨论】:

  • @egnd09 请记住,res.locals.mt 只会在后续的app.get/post/use 调用中设置。在您的问题示例中,console.log(res.locals.mt) 仅在 getMt() 回调函数内返回您期望的值。
【解决方案2】:

这能让你到达你想去的地方吗?

function getMt(user_id, callback) {
    var Model = require('./models/mt');
    Model.count({'users.user_id': user_id}, function(err, count) {
        if (err) {
            console.log(err.stack);
            return callback(0);
        }
        callback(count);
    });
}

【讨论】:

  • 这是一种更好的计数方法,但我无法让 val 设置 res.locals.mt,这是我的目标。对不起,我不清楚这个问题。要编辑它。
猜你喜欢
  • 2017-04-06
  • 2011-09-22
  • 2014-03-01
  • 2017-01-10
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 2011-12-08
  • 2023-04-06
相关资源
最近更新 更多