How to check if a string is valid MongoDB ObjectId in Node.js ?
Last Updated :
23 Sep, 2024
Checking if a string is valid mongoDB ObjectID is important while working with databases. It ensures accurate reference the the objects in databases. We can validate the ObjectId with the help of isValid function in MongoDB.
Prerequisites:
MongoDB ObjectId
MongoDB creates a unique 12 bytes ID for every object using the timestamp of respective Object creation. This ObjectId can be used to uniquely target a specific object in the database.
Structure:
- 4-byte timestamp value
- 5-byte random value
- 3-byte incrementing counter, initialized to a random value
It looks like this,
507f191e810c19729de860ea
How to Check Valid MongoDB ObjectId ?
During a normal backend workflow, the ObjectId might be received based on some computation or use operations. These might result invalid ObjectId and querying databases with the wrong ObjectId gives exception which is then handled later. We can use the ObjectId.isValid function from mongoDB to validate the correct ObjectId.
In this article, we will learn how to check if a string is valid MongoDB ObjectId.
Examples:
594ced02ed345b2b049222c5 --> Valid MongoDB ObjectId
geeks --> Invalid MongoDB ObjectId
Using MongoDB ObjectId.isValid
Mongoose & MongoDB provide a very useful function in ObjectId i.e. ObjectId.isValid("some_id") to validate a string for correct MongoDB ID.
ObjectId can be imported from native mongodb as well as mongoose package.
Import ObjectId
const ObjectId = require('mongodb').ObjectId;
or
const mongodb, {ObjectId} = require('mongodb');
const ObjectId = require('mongoose').Types.ObjectId;
or
const mongoose = require('mongoose');
ObjectId = mongoose.Types.ObjectId;Id;
Problem with isValid function
However, it ObjectId.isValid(id) returns true even for invalid strings with length 12.
For example :
String ID | ObjectId.isValid(id) | Expected Validation |
594ced02ed345b2b049222c5 | true | true |
geeks | false | false |
toptoptoptop | true X | false |
geeksfogeeks | true X | false |
Using ObjectId with String typecasting
To prevent such cases, another check can be added after default validator which would return true or false based on condition, (new ObjectId created from string) cast to string === string
i.e. (String)(new ObjectId(id)) === id
A function can be created as follows to check if a string is valid ObjectId or not:
const ObjectId = require('mongoose').Types.ObjectId;
function isValidObjectId(id){
if(ObjectId.isValid(id)){
if((String)(new ObjectId(id)) === id)
return true;
return false;
}
return false;
}
JavaScript
// Requiring ObjectId from mongoose npm package
const ObjectId = require('mongoose').Types.ObjectId;
// Validator function
function isValidObjectId(id){
if(ObjectId.isValid(id)){
if((String)(new ObjectId(id)) === id)
return true;
return false;
}
return false;
}
// Loading testcases into array
const testStrings = [ "594ced02ed345b2b049222c5","geeks",
"toptoptoptop","geeksfogeeks"];
// Validating each test case
for(const testcase of testStrings){
if(isValidObjectId(testcase))
console.log(testcase + " is a valid MongodbID");
else
console.log(testcase + " is not a valid MongodbID");
}
Output:
Results of this function are:
String ID | isValidObjectId(id) | Expected Validation |
594ced02ed345b2b049222c5 | true | true |
geeks | false | false |
toptoptoptop | false | false |
geeksfogeeks | false | false |
Summary
The MongoDB ObjectId can be validate using the ObectId.isValid funtion but it fails in some cases hence typecast the id's to string and then compare for more accurate results.
Similar Reads
How to Converting ObjectId to String in MongoDB In MongoDB, documents are uniquely identified by a field called ObjectId. While ObjectId is a unique identifier for each document there may be scenarios where we need to convert it to a string format for specific operations or data manipulation. In this article, we'll learn about the process of conv
4 min read
How to Check if Object is JSON in JavaScript ? JSON is used to store and exchange data in a structured format. To check if an object is JSON in JavaScript, you can use various approaches and methods. There are several possible approaches to check if the object is JSON in JavaScript which are as follows: Table of Content Using Constructor Type Ch
2 min read
How to Create Indexes in MongoDB using Node.js? MongoDB, a popular NoSQL database, provides powerful indexing capabilities to improve query performance. Indexes in MongoDB help in quickly locating documents and speeding up read operations. In this tutorial, we'll explore how to create indexes in MongoDB using Node.js. What is an Index in MongoDB?
3 min read
How to add range in the Collection of Mongodb using Node.js ? Mongoose.module is one of the most powerful external module of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server.Mongoose module provides several functions in order to manipulate the documen
2 min read
How to add Timestamp in Mongodb Collection using Node.js ? Timestamp: With the help of timestamp document in the collection of the MongoDB can be differentiated on the basis of time. We can add Timestamp in Mongodb Collection in Node.js using the following approach: Installing Module: Install the mongoose module using the following command: npm install mong
1 min read
How to Validate Data using joi Module in Node.js ? Joi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data. Introduction to joi It's easy to get started a
3 min read
How to Perform a findOne Operation in MongoDB using Node.js? The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fe
4 min read
How To Perform a Find Operation With Sorting In MongoDB Using Node.js? Performing a find operation with sorting in MongoDB using Node.js is a common task for developers working with databases. This guide will walk you through the process step-by-step, including setting up a MongoDB database, connecting to it using Node.js, performing a find operation, and sorting the r
3 min read
How to set the document value type in MongoDB using Node.js? Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 min read
How to replace one document in MongoDB using Node.js ? MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Inst
1 min read