Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Databases and Redis

Mongoose.Types.ObjectId call fails or shows as deprecated

ErrorClass 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.

  • Applies to Mongoose 8, Node.js 22
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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 "
  2. 2Match what you see, then jump to its fix

    1. 1TypeError: Class constructor ObjectId cannot be invoked without 'new' after upgrading to Mongoose 7 or laterObjectId is called as a functionFix
    2. 2ObjectId 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. 3An id check that used to pass now fails after the Mongoose 7 upgradeCode checks _bsontype to detect an ObjectIdFix

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

Did this fix it?

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

Did this fix it?

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 numbers

3Verify

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

Did this fix it?

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

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.