ObjectId in must be a single string of 12 bytes or a string of 24 hex characters on reloading the product page

Hey there everyone,
I was following the jumpstart ecommerce tutorial with mongo db, and I encountered this problem.

When I click on the card and go to the product page it works fine, but when i reload the product page it returns an error:`Error: ObjectId in must be a single string of 12 bytes or a string of 24 hex characters

The realm function for getting the product:

exports = function(arg){



    let collection = context.services.get("mongodb-atlas").db("store").collection("products");
  

  return collection.findOne({_id:BSON.ObjectId(arg)})};

Thank you for taking your time out to read this question.

Jumpstart Jumpstart - YouTube
Screen Recording of the issue: Screen Recording 2022-05-11 at 12.08.41 PM.mov - Google Drive

Regards,
Vaarun Sinha

1 Like

Did you find a resolution? Anyone from Mongo can chime in?

I’m having the same type of issue. But im trying something like this in an API:

const value = JSON.stringify(uid)
const palette = await db.collection("users").find({ _id: ObjectId(value) }).toArray()

when you reload, your page has only what you include in your URL and the things you have saved in the Browser’s cache.

In both cases, if you do not properly code what properties will be available to the page and how the page handles them are both left to the developer of the frontend.

In your case, it is clear that the page does not do that inside the products page, but relies on the product card to pass the id to it. since the id is not in the form MongoDB expects (most possibly it is just null or undefined) then you get that error.

Your issue has the same error for a different reason. JSON.stringify() will give an error if its arguments is not an object. You don’t seem to get an error in that step so uid is an object, and your value will be something like this:

value='{"id":"someIdValue"}'

see, the single quotes are surrounding those inner double quotes. you can now see why ObjectId() gave an error. value does not have a proper shape.

you have two options now depending on what uid holds.

const value = uid.id // directly use the id field if it is a proper formatted string
or
.....find( { _id : uid.id } ) // directly use the id field if it is a proper object id.