'TypeError: ObjectId is not a function

I m trying to add CRUD operation in my code.but when I am trying to load data and post data this error is showing.Although I have imported const { ObjectId } = require('mongodb').ObjectId; but don't know why error is occuring..

 app.get('/product/:id', async (req, res) => {
            console.log(req.params.id);
            const id = req.params.id;
            const query = { _id: ObjectId(id) };
            const result = await productCollection.findOne(query);
            res.send(result)
        })
 

error:

:id
D:\Node\warehouse-management-server-side-Yasmin-Akhter\index.js:42
            const query = { _id: ObjectId(id) };
                                 ^

TypeError: ObjectId is not a function


Solution 1:[1]

You are using destructuring to import ObjectId by doing:

const { ObjectId } = require('mongodb');

By using this, you have already reached into the mongodb object and grabbed the ObjectId property. In your statement, since you added .ObjectId after the call to require, you are then reaching into the ObjectId property looking for a property ObjectId, which would return the unexpected results you are seeing.

Remove the .ObjectId in your import statement, or change it to:

const ObjectId = require('mongodb').ObjectId

*Note you are no longer destructuring by removing the brackets on the left side of the equals

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1