so I have to check if a given input is a valid ObjectID
and if that returns true
I want to transform the value to a ObjectID
. Unfortunately the validation returns true for "zzzzzzzzzzzz" and throws an exception while transforming the value.
I get the following error
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
I tried to reproduce the problem:
const { ObjectID } = require("mongodb");
const value = "zzzzzzzzzzzz";
const isValid = ObjectID.isValid(value);
if (!isValid) { // this is true
throw new Error("invalid ID");
}
ObjectID.createFromHexString(value); // throws exception
So why does the validation return true
then? How can I fix that? My real project is a NestJs application so it would be nice to cast a value of type any
to a typesafe ObjectID
.
So why does the validation return true then?
Because the code. Line 338
Basically any valid input to the ObjectID
constructor will return true with ObjectID.isValid()
Hence, for your case ObjectID.isValid("zzzzzzzzzzzz")
is true because new ObjectID("zzzzzzzzzzzz")
is a valid operation.
More from an old documentation of node-mongodb-native driver
how about this:
const { ObjectID } = require("mongodb");
function isValidObjectID(id) {
try{
ObjectID.createFromHexString(id)
}catch(e){
return false
}
return true
}
console.log(`zzzzzzzzzzzz
isValid: ${isValidObjectID("zzzzzzzzzzzz")}`) // false
console.log(`5beec2f547643846af1d4dc3
isValid: ${isValidObjectID("5beec2f547643846af1d4dc3")}`) // true
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments