Description
version 6.0.12 mongoose
Reporting a bug
getting a type error when calling mongoose.Types.ObjectId()
error Value of type 'typeof ObjectId' is not callable. Did you mean to include 'new'?
What is the expected behavior?
should be able to call mongoose.Types.ObjectId()
without adding new
keyword.
What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.
version 6.0.12 mongoose
version 14.6.0 node
version 4.1.4 mongodb
the fault lies in any file calling the mongoose.Types.ObjectId()
I recently upgraded mongodb from 3.5.4
to 4.1.4
and mongoose from 5.12.10
to 6.0.12
as I am using typescript
4.4.4
and ts-node 10.4.0
in my project I get a type error Value of type 'typeof ObjectId' is not callable. Did you mean to include 'new'? when using this line of code mongoose.Types.ObjectId() I uninstalled and removed the @types/mongoose
from the project as the new version mongoose has its own type and removed globally also but still I get the same error.
Despite the fact that this issue #9608 was tagged as a bug and later tagged as resolved, I continue to receive this error.
Activity
root-io commentedon Nov 6, 2021
Can you try this:
zbarakzai commentedon Nov 6, 2021
I don't need it as a type my intention is to create an ObjectId instance like this
_id: variant._id ? variant._id : mongoose.Types.ObjectId(),
IslandRhythms commentedon Nov 8, 2021
possible that this https://mongoosejs.com/docs/migrating_to_6.html#objectid-valueof caused it but can you not just add the new keyword?
zbarakzai commentedon Nov 11, 2021
@IslandRhythms if I don't add the
new
KeywordTypescript
complains about the above error I mentioned.vkarpov15 commentedon Dec 9, 2021
I took a closer look and this is expected behavior. In MongoDB Node driver 4.x, ObjectId is now a class, and there's no way to allow calling a TS class without
new
.The reason why
Types.ObjectId()
works in JavaScript is that the MongoDB driver's TS compiler doesn't compile to ES6 classes, so the compiled JavaScript looks like this:In theory we might be able to make ObjectId an interface, but for some reason doing the below causes a
Property 'ObjectId' does not exist on type 'typeof Types'.
error.I'm adding a note to our migration guide.