Home > Enterprise >  CastError: Cast to ObjectId failed for value "XXXXXXXXXX" (type string) at path "_id&
CastError: Cast to ObjectId failed for value "XXXXXXXXXX" (type string) at path "_id&

Time:04-22

I'm a beginner.

when i'm testing route with wrong (short) ID, for example instead of "6261220286e8d5e7ee6f221e" i'm putting "6261220286e8d5e7ee6f221" node app crashes with this error:

Screenshot of Node ERROR

here is the route code:

router.put('/:id', async (req, res) => {
    //Validate with Joi
    const { error } = validateGenre(req.body);
    //If invalid, return 400 - Bad Request.
    if (error) return res.status(400).send(error.details[0].message);
    //Look up the genre and Update.
    const genre = await Genre.findByIdAndUpdate(req.params.id, { name: req.body.name }, { new: true })
    //If not exists, return 404.
    if (!genre) return res.status(404).send('The genre with the given ID was not found');
    //Return ubdated genre.
    res.send(genre);
});

function validateGenre(genre) {
    const schema = Joi.object({ name: Joi.string().min(3).max(50).required() });
    return schema.validate(genre);
}

here also Genre schema:

const genreSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        minlength: 5,
        maxlength: 50,
    }
});

const Genre = new mongoose.model('Genre', genreSchema);

My question is: How to handle this type of error, or how to validate requested ID length to return proper message to the client.

Sorry again, I'm really a beginner and thanks in advance.

CodePudding user response:

Have you tried using try catch ??, in catch section you can do response with status 500 and an error message thrown by Genre

  • Related