(error when fetching) BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

Please note that:

  • I’ve already read previous questions about this and no helpful advice was found.

Facing the BSONTypeError multiple times across the codebase.

router.put('/prerelease/:userId', [verifyUser, verifyHomeOwner], async (req, res) => {
  const data = req.body;
  console.log(
    req.params,
    isObjectIdOrHexString(req.params.userId),
    isValidObjectId(req.params.userId),
    new mongoose.Types.ObjectId(req.params.userId)
  );
}

The console log returns

{ userId: '66ed83c4a613750015d1225a' } true true new ObjectId('66ed83c4a613750015d1225a')

So it should work. The error does not offer any more context.
Already tried:

  • Transforming it to string
  • Transforming it to ObjectId
  • Transforming it using JSON.stringify
  • Tried using findById

I need to fix this or we’ll need to change to firestore

You would need to share the codebase that generates the error so that we can tell you what is wrong with your code.

With the log you shared it is clear that the code and data you shared does not the generate the error you mentioned, unless something was redacted. In particular, I am really surprised that the keyword new also appears in the console.log output. That differs from the output I am used to like

Note that the string 66ed…225a is a valid string to convert to an object id. But if your real code is like the one you share, where it seems you take data received from the web (userId) without any kind of validation, and then feed it to your API then it is destined to fail.

Trying to fix this by switching infrastructure like

won’t really fix the issue.

In situation like that we usually sanitize the input or try-catch to make sure we do not feed bad data to the other layers. Hackers will always try to feed you app with bad data, so you have to make sure it does not break your code.