Home > Blockchain >  How to fix Error: CastError: Cast to ObjectId failed for value (type string) at path "_id"
How to fix Error: CastError: Cast to ObjectId failed for value (type string) at path "_id"

Time:04-05

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

CodePudding user response:

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'

CodePudding user response:

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.

  • Related