MongoDB — How to Compare ObjectIds in Node.js

MongoDB requires each document to contain an _id field. If the _id field is not present when inserting a document, MongoDB generates an ObjectId for you.

ObjectIds have a length of 12 bytes: 4-byte timestamp, 5-byte random value, and 3-byte incrementing counter. An ObjectId can be formatted as a hex string that looks like 61dc2d31bbe643fc32022a5f.

The problem with ObjectIds: you can’t compare an ObjectId string with an ObjectId instance.

This tutorial shows you how to compare ObjectIds in Node.js.

Case Insensitive Sorting with Mongoose and MongoDB Series Overview

Compare MongoDB ObjectIds in Node.js

When using ObjectIds in your application, you may use them in the frontend (browser) as well. Requesting data for a given web page may use an ObjectId as an identifier for a given resource. Using identifiers in URLs requires a string representation for the request. In your backend, you need to convert the request parameters back to their original type.

Let’s imagine the following simplified code: you have an ObjectId in string format and a document using an ObjectId for the _id field.

Comparing the string ObjectId against the _id field in the user instance returns false:

const oid = '61dc2d31bbe643fc32022a5f'

const user = {  
  _id: ObjectId("61dc2d31bbe643fc32022a5f"),
  name: { first: "Future", last: "Studio" }
}

const isEqual = user._id === oid // wrong way 🚨  
// false

What you should do instead: use the objectId.equals method. Every ObjectId instance supports the equals method allowing you to provide your comparison value. The MongoDB Node.js driver resolves the given argument value and compares them:

const oid = '61dc2d31bbe643fc32022a5f'

const user = {  
  _id: ObjectId("61dc2d31bbe643fc32022a5f"),
  name: { first: "Future", last: "Studio" }
}

const isEqual = user._id.equals(oid) // ✅ right way  
// true

Enjoy comparing MongoDB ObjectIds!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.