Skip to content

kavingovind/joi-mongo-objectid

Repository files navigation

joi-mongo-objectid

A Simple Joi extension to validate and parse MongoDB ObjectId strings.

What

Allows you to do Joi.mongo().objectId().

Installation

$ npm install joi-mongo-objectid --save

or

$ yarn add joi-mongo-objectid

Requisites

"joi": ">=17.0.0",
"mongoose": ">=6.9.0"

Usage

const JoiBase = require("joi");
const { JoiObjectId } = require("joi-mongo-objectid");

const Joi = JoiBase.extend(JoiObjectId);

const schema = Joi.object({
  _id: Joi.mongo().objectId().required(),
});

const data = { _id: "67531b0516e6712d5cf56ca9" };
const result = schema.validate(data);

if (result.error) {
  console.error(result.error.message); // [Error [ValidationError]: ""_id"" did not seem to be a objectId]
} else {
  console.log(result); // { value: { id: new ObjectId('6752b3b125b75c18063a04b5') } }
}

License

MIT License

Authors