Home > front end >  mongoose objectId validation doesnt work correctly
mongoose objectId validation doesnt work correctly

Time:10-22

I tried somethin like these strings and it return true unexpectedly!!

  • mohamma22144
  • mohamma22145

is this function reliable enough?

mongoose.Types.ObjectId.isValid('mohamma22145')

CodePudding user response:

ObjectId.isValid(id) returns true even for invalid strings with length 12. For example :

String ID                |   ObjectId.isValid(id)  |    Expected Validation               
---------------------------------------------------------------------------
594ced02ed345b2b049222c5 |  true                   |  true
dania                    |  false                  |  false
toptoptoptop             |  true(but isnt)         |  false
daniandanian             |  true(but isnt)         |  false
---------------------------------------------------------------------------

To prevent such cases, another check can be added after default validator which would return true or false based on condition, (new ObjectId created from string) cast to string === string i.e. (String)(new ObjectId(id)) === id

A function can be created as follows to check if a string is valid ObjectId or not:

// Requiring ObjectId from mongoose npm package
const ObjectId = require('mongoose').Types.ObjectId;
  
// Validator function
function isValidObjectId(id){
      
    if(ObjectId.isValid(id)){
        if((String)(new ObjectId(id)) === id)
            return true;        
        return false;
    }
    return false;
}
  
// Loading testcases into array
const testStrings = [ "594ced02ed345b2b049222c5","geeks",  
                      "toptoptoptop","geeksfogeeks"];
  
// Validating each test case
for(const testcase of testStrings){
  
    if(isValidObjectId(testcase))
        console.log(testcase   " is a valid MongodbID");
    else
        console.log(testcase   " is not a valid MongodbID");
  
}

And the result would be:

String ID                |   ObjectId.isValid(id)  |    Expected Validation               
---------------------------------------------------------------------------
594ced02ed345b2b049222c5 |  true                   |  true
dania                    |  false                  |  false
toptoptoptop             |  false                  |  false
daniandanian             |  false                  |  false

CodePudding user response:

isValid() and isValidObjectId() returns true even the string is not an ObjectId. According to docs

Returns true if Mongoose can cast the given value to an ObjectId, or false otherwise.

If you want to check if is a real ObjectId you can use this RegEx: /^[a-f\d]{24}$/i

Example here:

var regex = new RegExp(/^[a-f\d]{24}$/i);
const ids = ['1', 'mohamma22145', '5a934e000102030405000000', 'FFFFFFFFFFFFFFFFFFFFFFFF']
ids.forEach(id => console.log(`${id} is an ObjectId: ${regex.test(id)}`))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related