Published on

Verify if a string is a valid MongoDB ObjectID with Mongoose

Authors

For my side project (personal finance app) to keep things simple, I have a helper function that takes in a string and uses it to query Account by its slug or id.

Here's how I did it using Mongoose's helper method isObjectIdOrHexString

How does it work?

It takes in a string and if it's an instance of Mongoose ObjectId or 24 character hex string then it returns true if not, then false

mongoose.isObjectIdOrHexString(new mongoose.Types.ObjectId()); // true
mongoose.isObjectIdOrHexString('62261a65d66c6be0a63c051f'); // true

mongoose.isObjectIdOrHexString('a1d5c138-e518-4b05-bc5a-390f5feae8e2'); // false
mongoose.isObjectIdOrHexString('nesin.io'); // false

Practical Example - Query Account by Slug or Id

// dep: npm install mongoose
import mongoose from "mongoose";
const { isObjectIdOrHexString } = mongoose;

const getAccountByIdOrSlug = (idOrSlug) => {
  const orFilter = {};
  if (isObjectIdOrHexString(idOrSlug)) {
    orFilter._id = idOrSlug;
  } else {
    orFilter.slug = idOrSlug;
  }

  return this.findOne({
    $and: [
      {
        $or: Object.keys(orFilter).map((key) => ({ [key]: orFilter[key] })),
      },
    ],
  }).lean(true);
};

Happy validating ObjectID!