Search code examples
mongooseobjectid

mongoose objectId validation doesnt work correctly


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

  • mohamma22144
  • mohamma22145

is this function reliable enough?

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

Solution

  • 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)}`))