Javascript Nodejs-如何使用express和mongoose在url中按名称路由?

Javascript Nodejs-如何使用express和mongoose在url中按名称路由?,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我有一台Express 4服务器,为作者提供CRUD路由: router.get('/authors', AuthorsController.index); router.post('/authors', AuthorsController.store); router.get('/authors/:name', AuthorsController.show); router.put('/authors/:name', AuthorsController.upda

我有一台Express 4服务器,为作者提供CRUD路由:

    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建立路由的最佳方法是什么?

您可以索引name字段,并在视图中按名称查找(假设名称是作者的属性)

这不需要更改数据库模型。如果需要,您可以通过id或名称进行搜索

比如说

 router.get('/authors/:name', AuthorsController.show);
将有以下视图

const AuthorsController = {
  async show(req, res){
    const authors = await Author.find({'name':req.params.name}).populate('books');
    res.send(authors);
  }
};

正如您在问题中提到的,您必须为名称生成slug,就像在模型中存储的空格或其他特殊字符中包含连字符一样。

您可以索引name字段,并在视图中按名称查找(假设名称是作者的属性)

这不需要更改数据库模型。如果需要,您可以通过id或名称进行搜索

比如说

 router.get('/authors/:name', AuthorsController.show);
将有以下视图

const AuthorsController = {
  async show(req, res){
    const authors = await Author.find({'name':req.params.name}).populate('books');
    res.send(authors);
  }
};

正如您在问题中所提到的,您必须为名称生成slug,就像在模型中存储的空格或其他特殊字符中包含连字符一样。

Hey welcome Shirish。谢谢你的回复!您是否能够在此答案中提供一个代码示例,说明它可能如何工作?在我的回答中添加了示例Hey welcome Shirish。谢谢你的回复!您是否能够在这个答案中提供一个代码示例,说明它可能如何工作?在我上面的回答中添加了一个示例