1

In my node js application, I have the following routes.

router.get('/:id', [auth], asyncHandler(async (req, res) => {
  const post = await postService.getPostById(req.params.id);
  res.json(post);
}));

router.get('/all', [auth], asyncHandler(async (req, res) => {
  const posts = await postService.getAllPosts(req.user.id);
  res.json(posts);
}));

Here, when I call the post/all route, it gets crashed. It says, Cast to ObjectId failed for value "all" at path "_id" for model "Post"Cast to ObjectId failed for value "all" at path "_id" for model "Post"

But if I comment the first route, second one works perfectly. Why is this happening?

Shashika Virajh
  • 8,497
  • 17
  • 59
  • 103
  • Does this answer your question? [Express routes parameter conditions](https://stackoverflow.com/questions/11258442/express-routes-parameter-conditions) – Sebastian Kaczmarek Nov 05 '19 at 09:19

2 Answers2

3

That is because /all also matches /:id. What you need to do is move /all above /:id:

// Match this first
router.get('/all', [auth], asyncHandler(async (req, res) => {
  const posts = await postService.getAllPosts(req.user.id);
  res.json(posts);
}));

// Then if not /all treat route as the variable `id`
router.get('/:id', [auth], asyncHandler(async (req, res) => {
  const post = await postService.getPostById(req.params.id);
  res.json(post);
}));
slebetman
  • 109,858
  • 19
  • 140
  • 171
1

because when you call /all route it will redirect to /:id route and try to convert all to objectId. so you need to change your route like this

router.get('/one/:id', [auth], asyncHandler(async (req, res) => {
  const post = await postService.getPostById(req.params.id);
  res.json(post);
}));

router.get('/all', [auth], asyncHandler(async (req, res) => {
  const posts = await postService.getAllPosts(req.user.id);
  res.json(posts);
}));`
Ankur Patel
  • 478
  • 3
  • 6
  • It doesn't redirect. It just matches first. Express routes are middlewares. And just like middlewares they form an internal list of filters that get processed **in sequence**. – slebetman Nov 05 '19 at 09:22