我看到了很多答案,但我仍然无法做到这一点。 我有一个简单的函数,我想返回一个查询的长度在Mongoose上查找。 它是这样:Node.js 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。
有人能指出我正确的方向吗? 在此先感谢。
什么确切的问题是请定义它。 – Parixit 2014-09-24 16:04:44
听起来像'.count()'的情况吗? – 2014-09-24 16:06:55
除了使用count(),你的'Model.find()'调用中的第二项应该是一个对象。试试这个查询:'Model.find({some:'query'},{token:true},function(err,list){})' – 2014-09-24 16:12:08