【发布时间】: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