什么是嵌套快速路由的DRY方法

时间:2015-03-19 12:39:29

标签: node.js express mongoose

我想有一个api,允许获取一个人的嵌套属性

router.get('/person/:id', fun.. router.get('/person/:id/name, fun... router.get('/person/:id/address, fun...

所有都是一个猫鼬计划的对象。查找person对象的最佳方法是什么?我觉得我应该使用router.use(/ person /:id)来查看这个人并以某种方式传递它。

1 个答案:

答案 0 :(得分:4)

检查app.param(),例如:

router.param('id', function(req, res, next, id) {
  Person.find(id, function(err, person) {
    if (err)next(err);
    else if (person) {
      req.person = person;
      next();
    } else {
      next(new Error('failed to load person'));
    }
  });
});

router.get('/person/:id', function() { /* ... */});
router.get('/person/:id/name', function() { /* ... */});
router.get('/person/:id/address', function() { /* ... */});

然后,您可以从Person访问req.person对象。