Search code examples
mongodbmongoose

Validate MongoDB ObjectId


Is there a way to validate a MongoDB ObjectId without actually hitting the MongoDB database at all? For example, the string value "5c0a7922c9d89830f4911426" should result in "true".


Solution

  • You can use .isValid() method on ObjectId, try in mongoose:

    var mongoose = require('mongoose');
    var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true