Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate MongoDB ObjectId

Is there a way to validate a MongoDB ObjectId without actually hitting the MongoDB database at all? For example, the string value "5c0a7922c9d89830f4911426" should result in "true".

like image 239
Raj Chaudhary Avatar asked Dec 08 '18 20:12

Raj Chaudhary


People also ask

What is a valid ObjectId?

ObjectId values are 12 bytes in length, consisting of: a 4-byte timestamp value, representing the ObjectId's creation, measured in seconds since the Unix epoch. a 5-byte random value generated once per process. This random value is unique to the machine and process.

Does Mongoose actually validate the existence of an object ID?

No, an ObjectId field that's defined in your schema as a reference to another collection is not checked as existing in the referenced collection on a save.

How does MongoDB compare ObjectId?

Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the . equals() method. With your example, results.

What is ObjectId in MongoDB?

An ObjectId is a 12-byte BSON type having the following structure − The first 4 bytes representing the seconds since the unix epoch. The next 3 bytes are the machine identifier. The next 2 bytes consists of process id. The last 3 bytes are a random counter value.


2 Answers

You can use .isValid() method on ObjectId, try in mongoose:

var mongoose = require('mongoose');
var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true
like image 68
mickl Avatar answered Oct 11 '22 00:10

mickl


Please note that in almost all scenarios you just have to handle the catch and not bother with the validity of the ObjectID since mongoose would complain throw if invalid ObjectId is provided.

Model.findOne({ _id: 'abcd' }).exec().catch(error => console.error('error', error));

Other than that you could either use the mongoose.Types.ObjectId.isValid or a regular expression: /^[a-fA-F0-9]{24}$/

like image 29
Akrion Avatar answered Oct 11 '22 00:10

Akrion