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() ?
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.