skip to Main Content

My current code for the /api/students/id route is as follows

router.get('/:id',asyncHandler(async(req,res)=>{
    const student = await Student.findById(req.params.id)

        if(student){
            
             res.json(student)

        }
        else{
            res.status(404).json({message: 'Student not found'})
        }

}))

export default router

When I hit the /api/students/{correct-Id} it gives me the correct students details
however if i change the correct-Id to something different it gives me the following error ,

enter image description here

but I am expecting the correct error which is the one i have added ‘Student not found’

Any help is appreciated. thanks

2

Answers


  1. Do you have this in your controller?

    try {
    ///
    } 
    catch (error) {
       res.status(404).json({mesage: error.message})      
    }

    If so, change error.message to ‘Student not found’

    Login or Signup to reply.
  2. The id that you are sending is not an objectId and you are directly passing it to findById function of your model and mongo does not recognise that as an objectId hence it is failing.

    for your error "student not found" you need to pass a valid objectId.

    If you need that error in case of invalid id too then you have to check first
    something like this

    But ideally in case of invalid objectId the error should be something like Invalid Id , because you are knowing it before that the data can not exists. "student not found" would be a wrong message.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search