Connor Leech
Connor Leech

Reputation: 18873

Nodejs - How to route by name in url with express and mongoose?

I have an Express 4 server with CRUD routes for authors:

    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). I'd instead like it to be the authors name so there are human readable URLs, like: /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?

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)

What's the best way to establish routes with human readable URLs for a CRUD REST API with Express and Mongoose?

Upvotes: 0

Views: 1587

Answers (1)

Shirish Goyal
Shirish Goyal

Reputation: 510

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.

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.

Upvotes: 2

Related Questions