我想要一个允许获取一个人的嵌套属性的 api
router.get('/person/:id', 有趣..
router.get('/person/:id/name, 好玩...
router.get('/person/:id/address, fun...
所有都是同一个 Mongoose 方案的对象。查找 person 对象的最佳方法是什么?我觉得我应该使用 router.use(/person/:id) 来查看这个人并以某种方式传递它。
最佳答案
检查 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() { /* ... */});
然后您可以从 req.person
访问您的 Person
对象。
关于node.js - 什么是嵌套快速路由的 DRY 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29144835/