MongoDB Node check if objectid is valid
node.jsMongodbnode.js Problem Overview
How can I check whether an ObjectID is valid using Node's driver
I tried :
var BSON = mongo.BSONPure;
console.log("Validity: " + BSON.ObjectID.isValid('ddsd'))
But I keep getting an exception instead of a true or false. (The exception is just a 'throw e; // process.nextTick error, or 'error' event on first tick'
node.js Solutions
Solution 1 - node.js
This is a simple check - is not 100% foolproof
You can use this Regular Expression if you want to check for a string of 24 hex characters.
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$")
checkForHexRegExp.test("i am a bad boy")
// false
checkForHexRegExp.test("5e63c3a5e4232e4cd0274ac2")
// true
Regex taken from github.com/mongodb/js-bson/.../objectid.ts
For a better check use:
var ObjectID = require("mongodb").ObjectID
ObjectID.isValid("i am a bad boy")
// false
ObjectID.isValid("5e63c3a5e4232e4cd0274ac2")
// true
isValid
code github.com/mongodb/js-bson/.../objectid.ts
Solution 2 - node.js
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))
Solution 3 - node.js
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
Solution 4 - node.js
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");
}
Solution 5 - node.js
@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;
}
Solution 6 - node.js
Below is my model where I am trying to validate subject id that is of type objectId data using JOI (Joi.objectId().required())
:
const Joi = require('joi');
const mongoose = require('mongoose');
const Category = mongoose.model('Category', new mongoose.Schema({
name: String
}));
function validateCategory(category) {
const schema = {
name: Joi.string().min(5).max(50).required(),
subject_id: Joi.objectId().required(),
};
return Joi.validate(category, schema);
}
exports.Category = Category;
exports.validate = validateCategory;
joi-objectid
validates that the value is an alphanumeric string of 24 characters in length.
Solution 7 - node.js
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()
Solution 8 - node.js
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'