How to determine if a string is a MongoDB ObjectID?

Sometimes, we want to determine if a string is a MongoDB ObjectID.

In this article, we’ll look at how to determine if a string is a MongoDB ObjectID.

How to determine if a string is a MongoDB ObjectID?

To determine if a string is a MongoDB ObjectID, we can use the mongoose.isValidObjectId method.

For instance, we write

mongoose.isValidObjectId(string);

to call mongoose.isValidObject with the string that we want to check if it’s an ObjectID.

It returns true if string is a valid ObjectID and false otherwise.

Conclusion

To determine if a string is a MongoDB ObjectID, we can use the mongoose.isValidObjectId method.