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
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
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.
MongoDB ObjectId validator for Joi.