节点和快速 - 使数据库可用于子目录中的所有页面

时间:2014-07-04 15:10:27

标签: node.js express routes node-mongodb-native

如何将这两个数据库集合提供给扩展名为/auth的所有路径? (例如:/auth/opentickets/auth/closedtickets/auth/editdeveloper)现在,我必须将此添加到每个事件处理程序。还有更好的方法吗?

router.get('/auth', function(req, res) {
    var db = req.db;
    // pull from users collection
    db.users.find({}, function(usererr, userdocs){
        if (usererr){ return usererr}
            // pull from developers collection
        db.developers.find({}, function(deverr, devdocs){
            if (deverr) {return deverr}
            res.render('developer', { title: 'Gizmo Ticket System', developers:devdocs, users:userdocs });
        });    
    });    
});

1 个答案:

答案 0 :(得分:1)

您可以在路由之前将逻辑放在中间件中:

router.use(['/auth', '/auth/*'], function(req, res, next) {
  var db = req.db;

  // pull from users collection
  db.users.find({}, function(usererr, userdocs){
    if (usererr)
      return next(usererr);

    // pull from developers collection
    db.developers.find({}, function(deverr, devdocs){
      if (deverr)
        return next(deverr);

      res.locals.title = 'Gizmo Ticket System';
      res.locals.developers = devdocs;
      res.locals.users = userdocs;
      next();
    });
  });
});

router.get('/auth', function(req, res) {
  res.render('auth-main');
});
router.get('/auth/closedtickets', function(req, res) {
  res.render('auth-closedtickets', { title: res.locals.title + ' - Closed Tickets' });
});
// ...

或者,如果您想要对所有这些路径进行完全相同的渲染:

router.get(['/auth', '/auth/*'], function(req, res, next) {
  var db = req.db;

  // pull from users collection
  db.users.find({}, function(usererr, userdocs){
    if (usererr)
      return next(usererr);

    // pull from developers collection
    db.developers.find({}, function(deverr, devdocs){
      if (deverr)
        return next(deverr);

      res.render('developer', {
        title: 'Gizmo Ticket System',
        developers: devdocs,
        users: userdocs
      });
    });
  });
});