Mongoose.Types.ObjectId call fails or shows as deprecated
Class constructor ObjectId cannot be invoked without 'new'Short answer
Since Mongoose 7, ObjectId is a JavaScript class, so calling mongoose.Types.ObjectId(id) without the new keyword throws. Write new mongoose.Types.ObjectId(id), which also works in Mongoose 6. Do not build ids from mongoose.ObjectId, which is the schema type, and replace _bsontype checks with the supported helpers.
Fix it fast
1Find out which cause you have
Find every place that builds an ObjectId. The calls that lack new are the ones to change.
grep -rnE "ObjectId\(" src/ | grep -v "new "2Match what you see, then jump to its fix
- 1
TypeError: Class constructor ObjectId cannot be invoked without 'new' after upgrading to Mongoose 7 or laterObjectId is called as a functionFix - 2
ObjectId creation works in a schema definition but gives wrong results or errors when used to make a valueThe schema type mongoose.ObjectId is used to create valuesFix - 3
An id check that used to pass now fails after the Mongoose 7 upgradeCode checks _bsontype to detect an ObjectIdFix
- 1
What does the error look like?
Class constructor ObjectId cannot be invoked without 'new'mongoose.Types.ObjectId(...) shown struck through as deprecated in the editor
Cause 1 of 3
ObjectId is called as a function
1Check
In Mongoose 6 and older, ObjectId could be created without new. In Mongoose 7 it became a class, so the call is an error.
grep -rnE "Types\.ObjectId\(|[^w] ObjectId\(" src/2Fix
Add new. The same form works in Mongoose 6, so you can change the code before upgrading.
const mongoose = require('mongoose');
// before: mongoose.Types.ObjectId(id)
const id = new mongoose.Types.ObjectId(idString);3Verify
Run the code path that failed. It builds the id without a TypeError.
node -e "const m=require('mongoose');console.log(new m.Types.ObjectId().toString())"Confirmed by mongoosejs.com
Cause 2 of 3
The schema type mongoose.ObjectId is used to create values
1Check
mongoose.ObjectId is the schema type used in definitions such as { owner: mongoose.ObjectId }. The Mongoose docs say not to use it to create an instance and to use mongoose.Types.ObjectId instead.
grep -rn "mongoose.ObjectId" src/2Fix
Keep mongoose.Schema.Types.ObjectId or mongoose.ObjectId in schemas only, and create values with mongoose.Types.ObjectId.
const ownerId = new mongoose.Types.ObjectId();
await Post.create({ title: 'Hello', owner: ownerId });3Verify
The saved document holds a valid ObjectId in the owner field.
const doc = await Post.findOne({ owner: ownerId }); console.log(doc !== null);Confirmed by mongoosejs.com
Cause 3 of 3
Code checks _bsontype to detect an ObjectId
1Check
The migration guide says the internal _bsontype property equals 'ObjectId' in Mongoose 7, and asks you to update places that use it to detect an ObjectId.
grep -rn "_bsontype" src/2Fix
Use the public helpers. isValidObjectId accepts anything Mongoose can cast to an ObjectId, and isObjectIdOrHexString accepts only an ObjectId or a 24-character hex string.
mongoose.isObjectIdOrHexString(value); // strict
mongoose.isValidObjectId(value); // anything castable, even numbers3Verify
Try one real ObjectId, one 24-character string and one random string.
node -e "const m=require('mongoose');console.log(m.isObjectIdOrHexString('0123456789ab'), m.isObjectIdOrHexString('507f1f77bcf86cd799439011'))"Confirmed by mongoosejs.com
How do I stop it coming back?
- Always write new mongoose.Types.ObjectId(...) and add a lint rule or a code search for ObjectId( without new.
- Use isObjectIdOrHexString when validating ids from request parameters, because isValidObjectId also accepts numbers and 12-character strings.
- Read the migration guide before a major Mongoose upgrade and run the test suite on a branch.
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
Databases
Node.js in Docker Compose cannot find mysql2/promise
The app works on the host but fails after docker compose up
mysql2/promise is a path inside the mysql2 package.
2 causes, each with a fixDatabases
Elasticsearch rejects requests with circuit_breaking_exception: Data too large
circuit_breaking_exception with a reason that contains Data too large
A circuit_breaking_exception with 'Data too large' means Elasticsearch refused work to protect a node's JVM heap.
3 causes, each with a fixDatabases
JupyterLab cannot determine its build status without Node.js
Could not determine jupyterlab build status without nodejs
JupyterLab itself runs without Node.js, but source extensions need Node.js to rebuild it.
3 causes, each with a fixDatabases
Mongoose cannot sign in to MongoDB Atlas: bad auth, authentication failed
MongoError: bad auth Authentication failed.
Authentication failed means the server rejected the user in your connection string.
3 causes, each with a fixDatabases
MongoDB says duplicate key, but the value is null
MongoServerError: E11000 duplicate key error
A unique index in MongoDB stores a missing field as null, and only one null entry is allowed.
3 causes, each with a fixDatabases
mongodb-memory-server will not start under Jest or in Docker
NoSystemBinaryFoundError
When mongodb-memory-server fails to start, the real reason is hidden behind a generic message.
4 causes, each with a fix