Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

362
Vistas
CastError: Cast to ObjectId failed for value "XXXXXXXXXX" (type string) at path "_id" for model "XXXX"

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda