How can I check whether an ObjectID is valid using Node\'s driver
I tried :
var BSON = mongo.BSONPure;
console.log(\"Validity: \" + BSON.ObjectID.is
Follow this regular expression :
in js
new RegExp("^[0-9a-fA-F]{23}$").test("5e79d319ab5bfb2a9ea4239")
in java
Pattern.compile("^[0-9a-fA-F]{23}$").matcher(sanitizeText(value)).matches()
You can use Cerberus and create a custom function to validate and ObjectId
from cerberus import Validator
import re
class CustomValidator(Validator):
def _validate_type_objectid(self, field, value):
"""
Validation for `objectid` schema attribute.
:param field: field name.
:param value: field value.
"""
if not re.match('[a-f0-9]{24}', str(value)):
self._error(field, ERROR_BAD_TYPE % 'ObjectId')
## Initiate the class and validate the information
v = CustomValidator()
schema = {
'value': {'type': 'objectid'}
}
document = {
'value': ObjectId('5565d8adba02d54a4a78be95')
}
if not v(document, schema):
print 'Error'
isValid()
is in the js-bson (objectid.ts) library, which is a dependency of node-mongodb-native.
For whoever finds this question, I don't recommend recreating this method as recommend in other answers. Instead, continue using node-mongodb-native
like the original poster was using, the following example will access the isValid()
method in js-bson
.
var mongodb = require("mongodb");
var objectid = mongodb.BSONPure.ObjectID;
console.log(objectid.isValid('53fbf4615c3b9f41c381b6a3'));
July 2018 update: The current way to do this is:
var mongodb = require("mongodb")
console.log(mongodb.ObjectID.isValid(id))
As an extension of Eat at Joes answer... This is valid in node-mongodb-native 2.0
var objectID = require('mongodb').ObjectID
objectID.isValid('54edb381a13ec9142b9bb3537') - false
objectID.isValid('54edb381a13ec9142b9bb353') - true
objectID.isValid('54edb381a13ec9142b9bb35') - false
@GianPaJ's snippet is great but it needs to be extended slightly to cover non hex objectID's. Line 32 of the same file indicates objectID's can also be 12 characters in length. These keys are converted to a 24 character hex ObjectID by the mongodb driver.
function isValidObjectID(str) {
// coerce to string so the function can be generically used to test both strings and native objectIds created by the driver
str = str + '';
var len = str.length, valid = false;
if (len == 12 || len == 24) {
valid = /^[0-9a-fA-F]+$/.test(str);
}
return valid;
}
If you are using mongoose
then you can use mongoose for validation rather than depending on any other library.
if (!mongoose.Types.ObjectId.isValid(req.id)) {
return res.status(400).send("Invalid object id");
}