Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.1K
Views
BSONTypeError: el argumento pasado debe ser una cadena de 12 bytes o una cadena de 24 caracteres hexadecimales

Necesito ayuda aquí. Intenté casi todo lo que encontré en Internet, pero no funcionó.

Entonces, este es mi código:

 const id = req.params.id.trim(); Blog.findById(id) .then((result) => { res.render("details", { blog: result, title: "Blog Details" }); }) .catch((err) => { console.log(err); }); };

Sucede cuando estoy tratando de crear un nuevo blog.

este es mi error:

 CastError: Cast to ObjectId failed for value "blogs" (type string) at path "_id" for model "Blog" at model.Query.exec (/Users/xxx/blogMongoDB/node_modules/mongoose/lib/query.js:4546:21) at model.Query.Query.then (/Users/xxx/blogMongoDB/node_modules/mongoose/lib/query.js:4645:15) at blog_details (/Users/xxx/blogMongoDB/controllers/blogController.js:19:10) at Layer.handle [as handle_request] (/Users/xxx/blogMongoDB/node_modules/express/lib/router/layer.js:95:5) at next (/Users/xxx/blogMongoDB/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/Users/xxx/blogMongoDB/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/Users/xxx/blogMongoDB/node_modules/express/lib/router/layer.js:95:5) at /Users/xxx/blogMongoDB/node_modules/express/lib/router/index.js:281:22 at param (/Users/xxx/blogMongoDB/node_modules/express/lib/router/index.js:354:14) at param (/Users/xxx/blogMongoDB/node_modules/express/lib/router/index.js:365:14) { messageFormat: undefined, stringValue: '"blogs"', kind: 'ObjectId', value: 'blogs', path: '_id', reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters at new BSONTypeError (/Users/xxx/blogMongoDB/node_modules/bson/lib/error.js:41:28) at new ObjectId (/Users/xxx/blogMongoDB/node_modules/bson/lib/objectid.js:65:23) at castObjectId (/Users/xxx/blogMongoDB/node_modules/mongoose/lib/cast/objectid.js:25:12) at ObjectId.cast (/Users/xxx/blogMongoDB/node_modules/mongoose/lib/schema/objectid.js:245:12) at ObjectId.SchemaType.applySetters (/Users/xxx/blogMongoDB/node_modules/mongoose/lib/schematype.js:1135:12) at ObjectId.SchemaType._castForQuery (/Users/xxx/blogMongoDB/node_modules/mongoose/lib/schematype.js:1567:15) at ObjectId.SchemaType.castForQuery (/Users/xxx/blogMongoDB/node_modules/mongoose/lib/schematype.js:1557:15) at ObjectId.SchemaType.castForQueryWrapper (/Users/xxx/blogMongoDB/node_modules/mongoose/lib/schematype.js:1534:20) at cast (/Users/xxx/blogMongoDB/node_modules/mongoose/lib/cast.js:336:32) at model.Query.Query.cast (/Users/xxx/blogMongoDB/node_modules/mongoose/lib/query.js:4969:12), valueType: 'string' }
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

mongodb _id es un ObjectID , por lo tanto, la mangosta necesita buscar el Objeto y no la cadena.

buena solución: const id = mongoose.Types.ObjectId(req.params.id.trim());

about 4 years ago · Juan Pablo Isaza Report

0

Convertir id a ObjectId :

 import { ObjectId } from "mongodb"; const convertedId = ObjectId(id)

Si la conversión no tiene éxito debido a una id no válida, puede detectar el error:

 try{ //your code }catch(e){ if(e instance of BSONTypeError){ //do whatever you need if this occurs } }

No olvides import { BSONTypeError } from "bson";

about 4 years ago · Juan Pablo Isaza Report

0

Su parámetro de solicitud must be a string of 12 bytes or a string of 24 hex characters Verifique el _id en sus parámetros de solicitud. Debe ser un 24 hexadecimal como este: 61d634706a98a61edd42bf45

Esto es solo la solución a su problema. Sería genial si alguien proporciona una buena práctica sobre este tema.

La pregunta es: ¿Qué pasa si el cliente busca con un _id no mide 24? ¿Por qué Mongoose arroja un error en lugar de simplemente devolver algo como "no se encontró la identificación"?

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!