MongoDB Schema Document Validator
Have you ever been losing your mind over that annoyingly vague Document failed validation
error
while trying to figure out which of the document properties are acutally causing it?
If so, despair no more because this module is designed to help exactly with that.
Usage
You first need to create and initialize the validator object with db object after the validation rules have been set up. Then you can use the validator giving it a collection name and a document you'd like to validate.
Example:
const MongoClient = ;const MongodbSchemaDocumentValidator isDocumentFailedValidationError = ; const mongoClient = 'mongodb://company';await mongoClient; const db = mongoClient;await db; const validator = db;await validator; // remember that initalize has to be called after the schema is attached to the collection const collection = db;const newDeveloper = naem: 'this property has a typo';try await collection; catch error if const validation = validator; console;
This will output
isValid: false errors: keyword: 'required' dataPath: '' schemaPath: '#/required' params: missingProperty: 'name' message: "should have required property 'name'" errorsText: "data should have required property 'name'"
which should point you in the right direction towards solving your problem.
Custom validation options
This module uses Ajv under the hood and you can configure it using its options. In order to use your custom configured Ajv instead of the default one, pass it as a second argument to the constructor:
const validator = db allErrors: true;
At the moment of writing this module is known to work well with Ajv version 6.12.4
.