MongoDB Node check if objectid is valid

Viewed 63918

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'

8 Answers

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");
}

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;

It will validate like this if anyone tries to send invalid objectId

joi-objectid validates that the value is an alphanumeric string of 24 characters in length.

MongoDB ObjectId validator for Joi.

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()

enter image description here

Related