Mongoose cannot turn the value you passed into an ObjectId for _id
CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"Short answer
Mongoose casts query values to the schema type, and throws CastError when it cannot. For _id that means the value is not an ObjectId or a 24-character hex string. A value shown as [object Object] is a whole object passed where the id string should be. Log the value, pass only the id, and validate it first.
Fix it fast
1Find out which cause you have
Log the exact value and its type just before the query. The error text shows only a string version of it.
console.log(typeof id, JSON.stringify(id)); console.log(require('mongoose').isObjectIdOrHexString(id));2Match what you see, then jump to its fix
- 1
The value in the message is [object Object]A whole object is passed where the id should beFix - 2
The message shows the plain string, such as :id or undefinedThe string is not a valid ObjectId (wrong length, a placeholder, or undefined text)Fix - 3
The unhandled CastError crashes the request or the processThe error is thrown by the query, so it must be caughtFix
- 1
What does the error look like?
CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"Cast to ObjectId failed for value "abc" (type string) at path "_id" for model "User"
Cause 1 of 3
A whole object is passed where the id should be
1Check
The object (for example req.body, a document, or { id: ... }) is passed to findById or as the _id filter. Mongoose docs list { test: 42 } as a value it cannot cast to an ObjectId.
console.log(typeof req.params.id, typeof req.body.userId);
console.log(JSON.stringify(req.body));2Fix
Pass the id string itself, not the object that contains it.
// wrong: User.findById(req.body)
const user = await User.findById(req.body.userId);3Verify
Repeat the request and check that the query now runs.
curl -s -X POST localhost:3000/user -H 'content-type: application/json' -d '{"userId":"62261a65d66c6be0a63c051f"}'Confirmed by mongoosejs.com
Cause 2 of 3
The string is not a valid ObjectId (wrong length, a placeholder, or undefined text)
1Check
A real id is an ObjectId or a 24-character hex string. isObjectIdOrHexString returns true only for those; isValidObjectId is looser and also accepts some 12-character strings and numbers.
const { isObjectIdOrHexString } = require('mongoose');
console.log(isObjectIdOrHexString('62261a65d66c6be0a63c051f')); // true
console.log(isObjectIdOrHexString('0123456789ab')); // false2Fix
Validate untrusted ids before querying and answer 400 instead of crashing.
if (!mongoose.isObjectIdOrHexString(req.params.id)) {
return res.status(400).json({ error: 'invalid id' });
}
const doc = await Model.findById(req.params.id);3Verify
Call the route with a bad and a good id.
curl -i localhost:3000/items/not-an-id
curl -i localhost:3000/items/62261a65d66c6be0a63c051fConfirmed by mongoosejs.com
Cause 3 of 3
The error is thrown by the query, so it must be caught
1Check
Mongoose says a query throws a CastError when it cannot cast a filter to the schema, so an await without try/catch rejects.
grep -rn "findById\|findOne" src | head2Fix
Catch it where you await the query and map it to a client error.
try {
const doc = await Model.findById(id);
} catch (err) {
if (err instanceof mongoose.Error.CastError) return res.status(400).end();
throw err;
}3Verify
Send a bad id and expect 400 instead of a stack trace.
curl -i localhost:3000/items/xyzConfirmed by mongoosejs.com
How do I stop it coming back?
- Validate every id that comes from a URL, body or query string.
- Use isObjectIdOrHexString for user input, because isValidObjectId is lenient.
- Do not hand request bodies straight to query filters.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
ng serve says it cannot determine the project or target
Cannot determine project for command.
The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.
3 causes, each with a fixBack end
ng fails with Cannot find module @angular/cli/bin/ng
Cannot find module '@angular/cli/bin/ng'
The ng command is the entry point to the Angular CLI package.
2 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
ng serve cannot find the dev-server builder package
Could not find the implementation for builder @angular/build:dev-server
The builder named in angular.json (for example @angular-devkit/build-angular:dev-server) is looked up as an npm package starting from the workspace root.
3 causes, each with a fixBack end
Angular build says it cannot resolve '@angular/localize/init'
Can't resolve '@angular/localize/init' in '/usr/src/app/src'
The build imports @angular/localize, and that package is not in node_modules.
2 causes, each with a fixBack end
The command npm run build -- --prod exited with code 1 (Angular)
The command "npm run build -- --prod" exited with code 1
Exit code 1 only says the build failed; the real message is above it.
2 causes, each with a fix