Soumi Ghosh
Soumi Ghosh

Reputation: 119

The signature '(inputId: number): ObjectId' of 'ObjectId' is deprecated, use static createFromTime() to set a numeric value for the new ObjectId

I am trying to fetch a single product using ObjectId, but wherenever I am writing the code:

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

   static findById(product_id)
    {
        // console.log("Collected product id:",product_id);
        //db is the database
         return db.collection('Product_data').find({"_id":new ObjectId(product_id)}).next()
        .then(singleData=>{
            return singleData;
        })
        .catch(err=>{
            console.log("Product not found",err)
        })
    }

It is giving a strike through over the ObjectId, though I am getting the result. Can anyone help to use createFromTime() ?

Upvotes: 6

Views: 7906

Answers (2)

levente.nas
levente.nas

Reputation: 489

With the new MongoDB driver for NodeJS, the BSON compatibility changed to bson^6.0.0 (see this Component Support Matrix). In bson^6.0.0 the ObjectId() constructor was marked deprecated, and that is why you’re getting this error. ObjectIds for queries can be created using the ObjectId methods createFromBase64, createFromHexString, or createFromTime.

Assuming your product_id is in HexString format (this should be the case by default) you can simply replace

new ObjectId(product_id)

with

ObjectId.createFromHexString(product_id).

If your ObjectId format is in Base64 or Time formats then use the corresponding ObjectId methods.

Upvotes: 26

WeDoTheBest4You
WeDoTheBest4You

Reputation: 1897

As @Joe has pointed out, the content of the variable product_id must be checked further.

If you use Mongo shell, please start it and execute the following statement over there.

new ObjectId(<substitute the context of your product_id>)

The output would help you to know the reason.

Upvotes: -1

Related Questions