Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

364
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda