2014-09-24 103 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