[英]Nodejs - How to route by name in url with express and mongoose?
I have an Express 4 server with CRUD routes for authors: 我有一个具有作者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);
Most tutorials I find will have the routes be /authors/:id
and then do Author.findById(req.params.id)
. 我发现的大多数教程的路由都是
/authors/:id
,然后执行Author.findById(req.params.id)
。 I'd instead like it to be the authors name so there are human readable URLs, like: /authors/jk-rowling
. 取而代之的是,我希望它是作者的名字,因此有一些可读的URL,例如:
/authors/jk-rowling
。
Do I need to store the hyphenated string on the Authors model, what's the best way to achieve this with express and Mongoosejs? 我是否需要将连字符的字符串存储在Authors模型上,用express和Mongoosejs实现此目的的最佳方法是什么?
My authors controller currently looks like this: 我的作者控制器当前看起来像这样:
const AuthorsController = {
async index(req, res){
const authors = await Author.find().populate('books');
res.send(authors);
}
};
(I'm using express-async-errors package for the async-await functionality with express) (我正在将express-async-errors包用于带有express的async-await功能)
What's the best way to establish routes with human readable URLs for a CRUD REST API with Express and Mongoose? 为带有Express和Mongoose的CRUD REST API建立具有人类可读URL的路由的最佳方法是什么?
You can index name field and in your views, find by name (assuming name is attribute of Author) 您可以索引名称字段,并在视图中按名称查找(假设名称是“作者”的属性)
This requires no change in terms of db model. 这不需要更改数据库模型。 You can search via both id or name if needed.
您可以根据需要通过ID或名称进行搜索。
For example 例如
router.get('/authors/:name', AuthorsController.show);
will have below view 将有下面的看法
const AuthorsController = {
async show(req, res){
const authors = await Author.find({'name':req.params.name}).populate('books');
res.send(authors);
}
};
As you mentioned in problem, you will have to generate slug for name like one containing hyphens in place of spaces or other special characters which will be stored in model as well. 正如你在问题中提到,你将不得不产生像含代替空格或其他特殊字符连字符一个将被存储在模型和名称蛞蝓 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.