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