Can I determine if a string is a MongoDB ObjectID? Can I determine if a string is a MongoDB ObjectID? express express

Can I determine if a string is a MongoDB ObjectID?


I found that the mongoose ObjectId validator works to validate valid objectIds but I found a few cases where invalid ids were considered valid. (eg: any 12 characters long string)

var ObjectId = require('mongoose').Types.ObjectId;ObjectId.isValid('microsoft123'); //trueObjectId.isValid('timtomtamted'); //trueObjectId.isValid('551137c2f9e1fac808a5f572'); //true

What has been working for me is casting a string to an objectId and then checking that the original string matches the string value of the objectId.

new ObjectId('timtamtomted'); //616273656e6365576f726b73new ObjectId('537eed02ed345b2e039652d2') //537eed02ed345b2e039652d2

This work because valid ids do not change when casted to an ObjectId but a string that gets a false valid will change when casted to an objectId.


You can use a regular expression to test for that:

CoffeeScript

if id.match /^[0-9a-fA-F]{24}$/    # it's an ObjectIDelse    # nope

JavaScript

if (id.match(/^[0-9a-fA-F]{24}$/)) {    // it's an ObjectID    } else {    // nope    }


✅ Build In Solution isValidObjectId() > Mongoose 5.7.12

If you are using Mongoose, we can test whether a String is of 12 bytes or a string of 24 hex characters by using mongoose build-in isValidObjectId.

mongoose.isValidObjectId(string); /* will return true/false */