【发布时间】:2019-07-31 22:15:04
【问题描述】:
我有一个为作者提供 CRUD 路由的 Express 4 服务器:
router.get('/authors', AuthorsController.index);
router.post('/authors', AuthorsController.store);
router.get('/authors/:name', AuthorsController.show);
router.put('/authors/:name', AuthorsController.update);
router.delete('/authors/:name', AuthorsController.remove);
我发现的大多数教程的路线都是/authors/:id,然后是Author.findById(req.params.id)。我希望它是作者的名字,所以有人类可读的 URL,例如:/authors/jk-rowling。
我是否需要将连字符字符串存储在 Authors 模型中,使用 express 和 Mongoosejs 实现此目的的最佳方法是什么?
我的作者控制器当前如下所示:
const AuthorsController = {
async index(req, res){
const authors = await Author.find().populate('books');
res.send(authors);
}
};
(我正在使用 express-async-errors 包来实现带有 express 的异步等待功能)
为使用 Express 和 Mongoose 的 CRUD REST API 建立具有人类可读 URL 的路由的最佳方法是什么?
【问题讨论】:
标签: javascript node.js mongodb express mongoose