I am new to coding and trying to build an APi using NOde js, express and mongodb
here is my code
router.get('/:id', async(req, res) => {
console.log(req.params.id);
try{
const show = await Show.findById(req.params.id);
const _iD = show._id.toHexString()
console.log(_iD );
if(req.params.id === _iD){
res.json(show);
} else {
res.send("not right ID");
}
}
catch(err){
console.log("error" err)
}
})
it not working out,if "you enter a wrong ID intentionally " and should get " not right ID ", but it gets "Cast to Object ID failed for value".
CodePudding user response:
Try out this function
function isMongooseId(id) {
var valid = false;
try{
if(id == mongoose.Types.ObjectId("" id)) valid = true;
} catch(e){
valid = false;
}
return valid;
}
// You can use it like this,
if(isMongooseId(req.params.id)) {
// Perform your db operation
}
CodePudding user response:
Make sure the "intentionally wrong ID" still respect the objectId syntax (24 hexadecimal characters i would say). Otherwise you will fail at the Show.findById
and jump right into the catch
.
Then, i'm not sure of what your trying to do.
If you provide an ID that is not present in the collection, Show.findById
will not return any object so you won't be able to get its ID with show._id.toHexString()
and you will, again, jump to the catch
.
And if the ID is in the collection, req.params.id === _iD
will always be true and you will never reach the else.
Instead you should just check if show contain an object