BSONTypeError: Argument passed in must be a string of 12 bytes or a st...You must be signed in to create a new issue
You must be signed in to create a new issue
closed
was closed 366 days ago
Issue Details
messageFormat: undefined, stringValue: '"[object Object]"', kind: 'ObjectId', value: '[object Object]', path: '_id', reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer at new BSONTypeError (C:\Users\user\OneDrive\test\test\backend\node_modules\bson\lib\error.js:41:28) at new ObjectId (C:\Users\user\OneDrive\test\test\backend\node_modules\bson\lib\objectid.js:67:23) at castObjectId (C:\Users\user\OneDrive\test\test\backend\node_modules\mongoose\lib\cast\objectid.js:25:12) at ObjectId.cast (C:\Users\user\OneDrive\test\test\backend\node_modules\mongoose\lib\schema\objectid.js:246:12) at ObjectId.SchemaType.applySetters (C:\Users\user\OneDrive\test\test\backend\node_modules\mongoose\lib\schematype.js:1201:12) at ObjectId.SchemaType._castForQuery (C:\Users\user\OneDrive\test\test\backend\node_modules\mongoose\lib\schematype.js:1648:15) at ObjectId.SchemaType.castForQuery (C:\Users\user\OneDrive\test\test\backend\node_modules\mongoose\lib\schematype.js:1636:15) at ObjectId.SchemaType.castForQueryWrapper (C:\Users\user\OneDrive\test\test\backend\node_modules\mongoose\lib\schematype.js:1612:20) at cast (C:\Users\user\OneDrive\test\test\backend\node_modules\mongoose\lib\cast.js:347:32) at model.Query.Query.cast (C:\Users\user\OneDrive\test\test\backend\node_modules\mongoose\lib\query.js:5312:12), valueType: 'string' }
Solutions
Submitted by Tajwar Saiyeed
You can create middleware to resolve the error
const errorHandler = (err, req, res, next) => { let statusCode = res.statusCode === 200 ? 500 : res.statusCode; let message = err.message; if (err.name === "CastError" && err.kind === "ObjectId") { statusCode = 404; message = "Resource not found"; } res.status(statusCode).json({ message, stack: process.env.NODE_ENV === "production" ? null : err.stack, }); next(); }; module.exports = { notFound, errorHandler };
And use it to your main index (server file).js.
Submitted 366 days ago
T