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

268
Vistas
keep getting this errror :" Cast to ObjectId failed for value" using mongodb with nodejs

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".

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

0

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
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

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

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