Validate MongoDB ObjectId

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

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

Please note that in almost all scenarios you just have to handle the catch and not bother with the validity of the ObjectID since mongoose would complain throw if invalid ObjectId is provided.

Model.findOne({ _id: 'abcd' }).exec().catch(error => console.error('error', error));

Other than that you could either use the mongoose.Types.ObjectId.isValid or a regular expression: /^[a-fA-F0-9]{24}$/


@mickl's Answer will be failed for the strings with the length of 12.

You should convert any given string to MongoDB ObjectId using ObjectId constructor in mongodb and then cast it to a string and the check again with the original one. It should be the same.

  import { ObjectId } from 'mongodb'

  function isValidId(id) {

     return new ObjectId(id).toString() === id;
  }

  isValidId('5c0a7922c9d89830f4911426')// true
  isValidId('lkjyuhgfdres')// false