2014-09-24 83 views
0

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

有人能指出我正確的方向嗎? 在此先感謝。

+0

什麼確切的問題是請定義它。 – Parixit 2014-09-24 16:04:44

+0

聽起來像'.count()'的情況嗎? – 2014-09-24 16:06:55

+0

除了使用count(),你的'Model.find()'調用中的第二項應該是一個對象。試試這個查詢:'Model.find({some:'query'},{token:true},function(err,list){})' – 2014-09-24 16:12:08

回答

0

致電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!!! 
      }); 
     } 
.... 
} 
+0

這個伎倆。非常感謝。 – egnd09 2014-09-24 16:39:26

+0

@ egnd09請記住,'res.locals.mt'只會在後續的'app.get/post/use'調用中設置。在你的問題示例中,'console.log(res.locals.mt)'只會在getMt()'回調函數內返回你期望的值。 – 2014-09-24 16:43:45

0

這是否讓你想要去的地方?

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); 
    }); 
} 
+0

這是一個更好的方法來計數,但我不能得到val設置res.locals.mt,這是我的目標。對不起,我不清楚這個問題。要編輯它。 – egnd09 2014-09-24 16:16:22