我看到了很多答案,但我仍然無法做到這一點。 我有一個簡單的函數,我想返回一個查詢的長度在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