Yashwanth K
Yashwanth K

Reputation: 301

Class constructor ObjectId cannot be invoked without 'new' in mongoose

When I send data from frontend to backend via API request I got this error:

Class constructor ObjectId can not be invoked without 'new' in mongoose,

I tried to convert into string and also into int but it didn't work.....

Upvotes: 13

Views: 17996

Answers (4)

Md. Rumon Khan
Md. Rumon Khan

Reputation: 177

This solution is for Node.js and MongoDB Server

I solved this problem by using new keyword


      const query =  {
        _id: new ObjectId(id),
      };

Upvotes: 0

Imp Pinkman
Imp Pinkman

Reputation: 91

Object id = "649beed348b20e1b8e7bca95";

You can pass this like:

new ObjectId(id);

Upvotes: 9

Abhijit Kumar
Abhijit Kumar

Reputation: 311

Just add the new keyword in front of objectId() function, it will work. For example:

const documentToFind = { _id: new ObjectId("649beed348b20e1b8e7bca95") };

There is the difference in the usage of objectId function in the driver connection for nodejs where you have need use it as constructor. Reference: https://mongodb.github.io/node-mongodb-native/5.6/classes/BSON.ObjectId.html

If you are using the function in the MongoDB directly for query, you can use

ObjectId("649beed348b20e1b8e7bca95")

Reference: https://www.mongodb.com/docs/v6.3/reference/method/ObjectId/#examples

Upvotes: 5

Yashwanth K
Yashwanth K

Reputation: 301

I am new to nodejs too, i am trying to post some questions, even answers that i am not able to find.

Here the problem not from frontend and backend, it is from mongoose schema

when we are converting data to objectId we just need to declare new

.

Solution: new mongoose.Types.ObjectId(Id)

If you find helpful then like the answer so others reach fast.

Upvotes: 17

Related Questions