Home > Software engineering >  why the mongoose.findById is failing when I pass an id in the url which is wrong?
why the mongoose.findById is failing when I pass an id in the url which is wrong?

Time:01-22

here is the code of mine

router.get('/:id', async (request, response) => {
    try{
        const user_obj = await User.findById(request.params.id);
        if (! user_obj) return response.status(404).send("No course found with the given id.");
        return response.send(user_obj);
    }
    catch(error){
        console.log(error);
    }
    return response.status(400).send("done.");
});

what i am trying to do is to catch the exact reason of failing which is obviously we all know object id is not correct.

i do have tried to wrap it in a try catch block and to get the error message from the error but it says

BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

which is not really descriptive why it is happening.

CodePudding user response:

You have to validate request.params.id before passing it to that function.

import mongoose from 'mongoose'

router.get('/:id', async (request, response) => {
  try {
    const { id } = request.params
    if (!mongoose.Types.ObjectId.isValid(id)) throw new Error('invalid id') // validating `id`

    const user_obj = await User.findById(id)
    if (!user_obj) return response.status(404).send('No course found with the given id.')
    
    response.send(user_obj)
  } catch (error) {
    console.error(error)
    // next(error)
    response.status(501).send('internal server error')
  }
})

Also you should be using response.json(...) instead of response.send(...)

CodePudding user response:

Convert the type of id from string to mongoose objectID(default for _id).

const id = mongoose.Types.ObjectId(req.params.id.trim());
  • Related