[英]Node.js Mongoose callback
I saw a lot of answers but im still unable to make this work. 我看到了很多答案,但是我仍然无法完成这项工作。 I have a simple function that i want to return a length of a query find on Mongoose.
我有一个简单的函数,我想返回一个在Mongoose上找到的查询的长度。 It goes like:
就像这样:
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);
});
}
I read a lot about async, and i still cant find a solution for this. 我阅读了很多有关异步的内容,但仍然找不到解决方案。 res.locals.mt still shows me undefined after the res.locals.mt = val inside the callback.
在回调内的res.locals.mt = val之后,res.locals.mt仍显示未定义。
Can someone point me in the right direction? 有人可以指出我正确的方向吗? Thanks in advance.
提前致谢。
Does this get you where you're trying to go? 这会把您带到您要去的地方吗?
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);
});
}
call next
function! 调用
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!!!
});
}
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.