【问题标题】:Nodejs - How to route by name in url with express and mongoose?Nodejs - 如何使用express和mongoose在url中按名称路由?
【发布时间】: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


    【解决方案1】:

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

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

    例如

     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,例如包含连字符代替空格或其他特殊字符的名称,这些字符也将存储在模型中。

    【讨论】:

    • 你好,欢迎 Shirish。谢谢回复!您能否在此答案中提供代码示例来说明它可能如何工作?
    • 在我上面的回复中添加了示例
    猜你喜欢
    • 2017-04-01
    • 2018-05-16
    • 2019-11-18
    • 2020-04-24
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多