Get a item by _id the database by passing a parameter

Here is my function

exports = async function(id) {

  const mongodb = context.services.get("mongodb-atlas");
  const db = mongodb.db("testproducts");
  const collection = db.collection("products");

  return await collection.findOne({"_id": new BSON.ObjectId(id)});

};

I am passing in the ID and when I return it I get “12345…efb” and its a 24-character string, if I manually input that string into where BSON.ObjectId("12345.....efb")});
I get the result back but passing it as a parameter its not working saying that ObjectId a strring of 12 bytes or 24 hex.

Please print out the value of id just before your findOne() and share the result.

Before I have created the function where I made it just return id; so I know that the comment on the function the id is the value of the object, if I were to do this function as on the second return I get the object in the return however when I use the parameter I get the error as stated above.

exports = async function(id) //63f445264c0d37a80727b25c
{

  const mongodb = context.services.get("mongodb-atlas");
  const db = mongodb.db("testproducts");
  const collection = db.collection("products");
   
  return await collection.findOne({"_id":  new BSON.ObjectId(id)});

  return await collection.findOne({"_id": new BSON.ObjectId("63f445264c0d37a80727b25c")});
};

Please print out the value of id and the value of typeof id before your findOne() and share the result.

Please share the code that calls your function.

It was on the client side react-native

var strproductid = String(productid);
const resultOfCallFunction = await user.functions.getItemByID(strproductid);

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.