admin管理员组

文章数量:1355540

Need some help here. Tried almost everything that I found at the internet, but didn't works.

So, this is my code:

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

it's happens when I'm trying to create a new blog.

this is my 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'
}

Need some help here. Tried almost everything that I found at the internet, but didn't works.

So, this is my code:

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

it's happens when I'm trying to create a new blog.

this is my 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'
}
Share Improve this question asked Dec 1, 2021 at 20:00 cdeluchicdeluchi 11 gold badge1 silver badge1 bronze badge 1
  • If you console.log req.params.id what value are you getting? – timewastingprofessional Commented Dec 2, 2021 at 1:05
Add a ment  | 

12 Answers 12

Reset to default 2

Your request parameter must be a string of 12 bytes or a string of 24 hex characters Check the _id in your request params. It must be a 24 hex number such as this: 61d634706a98a61edd42bf45

This may solve your problem. It would be great if someone could provide more info about this subject.

The question is: What if the client searches for an _id that doesn't have a length of 24? Why is Mongoose throwing an error instead of just returning something like "id not found"?

Convert the type of id from string to mongoose objectID(default for _id).

const id = mongoose.Types.ObjectId(req.params.id.trim());

mongodb _id is an ObjectID therefore the mongoose need to look-up the Object and not the string.

nice solution: const id = mongoose.Types.ObjectId(req.params.id.trim());

Your handler app.get('/blogs/create') need to go ABOVE your handler app.post('/blogs/:id').

CastError: Cast to ObjectId failed for value "blogs" ==> this means that the actual value of "const id = req.params.id.trim()" is the string "blogs" and this "blogs" is not a string of 12 bytes or a string of 24 hex characters that Blog.findById(id) is expecting.

https://mongoosejs./docs/schematypes.html#objectids

try to check the value of the id then make sure you're sending the correct value from the front-end

Convert id to ObjectId:

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

If conversion is not successful due to invalid id, then you can catch error:

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

Don't forget to import { BSONTypeError } from "bson";

In my case..
I was adding an object when I should have added a string.

const id = req.params

this code gave me an object, so I had to select the id inside that object.

const id = req.params.streamId;

And if it still does not work, then add .toString() at the end

Convert the type of id from string to mongoose objectID(default for _id).

const id = mongoose.Types.ObjectId(req.params.id.trim());

you can't transform a normal string to an ObjectId, check the param.id before use it.

you can use ObjectId.isValid("YOUR ID STRING") to test it.

i once had a similar problem If you have a handler app.get('/blogs/create') place it ABOVE your handler app.get('/blogs/:id').

This error is due to express trying to interpret create which is of type string in the url blogs/*create* as an id.

new mongoose.Types.ObjectId(req.query.sId)

i would suggest delete node and mongoDB and try to install again,if you have tried all method and nothing work reinstall monogdb and node .its work form me atleast tho.make sure you backup document before deleting all.good luck

本文标签: