Validate MongoDB ObjectIds

MongoDB uses ObjectId values as document identifiers by default.

A typical ObjectId is represented as a 24-character hexadecimal string.

Before querying MongoDB, validate the identifier using Mongoose.

Mongoose provides mongoose.isValidObjectId() to check whether a value can be cast to an ObjectId.

For APIs that require a strict 24-character hexadecimal representation, use an explicit regular expression as well.

Validate User ID
import mongoose from 'mongoose';

export function isValidUserId(userId) {
  return (
    typeof userId === 'string' &&
    /^[a-fA-F0-9]{24}$/.test(userId) &&
    mongoose.isValidObjectId(userId)
  );
}

Checks that the supplied ID is a string, contains exactly 24 hexadecimal characters, and is accepted by Mongoose.

Key Takeaways
  • MongoDB ObjectIds have a standard 24-character hexadecimal representation.

  • Validate IDs before database queries.

  • Return a client error for malformed identifiers.