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"
.
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.
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.
Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the . equals() method. With your example, results.
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.
You can use .isValid() method on ObjectId, try in mongoose:
var mongoose = require('mongoose');
var isValid = mongoose.Types.ObjectId.isValid('5c0a7922c9d89830f4911426'); //true
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}$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With