I have a route /api/:id
where :id has to be of type ObjectId.
Because following is the query I am runnuing
const data = await Person.find({_id:req.params.id})
It works fine if :id is of type ObjectId
but if user explicitly runs the api lets say /api/anything
, then Mongoose throughs an error
CastError: Cast to ObjectId failed for value "anything" at path "_id"
So, I would like to check if req.params.id
is of type ObjectId
and perform further operations only if it is.
Thus code would look like
if(checkObjectId(req.params.id)) {
const data = await Person.find({_id:req.params.id})
}