Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to check if a string is valid MongoDB ObjectId in Node.js ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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
During a normal backend workflow, the ObjectId might be received based on some computation or user operations. These might result invalid ObjectId and querying database with wrong ObjectId gives exception which is then handled later.

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

Prerequisites:

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 from mongodb or mongoose packages:

  • Using Mongodb:
const ObjectId = require('mongodb').ObjectId;
or
const mongodb, {ObjectId} = require('mongodb');

Using Mongoose:

const ObjectId = require('mongoose').Types.ObjectId;
or
const mongoose = require('mongoose');
ObjectId = mongoose.Types.ObjectId;Id;

However, it ObjectId.isValid(id) returns true even for invalid strings with length 12.
For example :

String IDObjectId.isValid(id)           Expected Validation               
594ced02ed345b2b049222c5truetrue
geeksfalsefalse
toptoptoptoptrue     Xfalse
geeksfogeekstrue     Xfalse

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 IDisValidObjectId(id)          Expected Validation         
594ced02ed345b2b049222c5truetrue
geeksfalsefalse
toptoptoptopfalsefalse
geeksfogeeksfalsefalse

 


My Personal Notes arrow_drop_up
Last Updated : 18 Apr, 2022
Like Article
Save Article
Similar Reads
Related Tutorials