0

I have a route handler that take the id parameter from request object and uses it to find a document. enter image description here

I thought that the findById function would return null if it doesn't find any document with the given id. So I created an if condition which generate an error with the appropriate message and status code. But it turns out the function automatically returns the following error if the id is invalid

enter image description here

But I do not want the "findById" query to generate error by itself. I want the tour variable to be null if the id is invalid so that my own implementation for handling 'Not found' exception works. How may I do so?

samman adhikari
  • 571
  • 1
  • 7
  • 17

1 Answers1

0

Try wrapping the line const tour = await Tour.findById(req.params.id) with a try catch statement like this:

try {
    const tour = await Tour.findById(req.params.id);
} catch (error) {
    next(new AppError(error.message, 404));
}

this won't solve the problem completely as you still need to convert the value of the id you're trying to query (I assume you're receiving a string) to a mongoose ObjectId. see this answer for this

Firas
  • 16
  • 2