A Simple Joi extension to validate and parse MongoDB ObjectId strings.
Allows you to do Joi.mongo().objectId()
.
$ npm install joi-mongo-objectid --save
or
$ yarn add joi-mongo-objectid
"joi": ">=17.0.0",
"mongoose": ">=6.9.0"
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') } }
}