In order to enhance the quality of our data stored in MongoDB database, we have decided to implement JSON Schema validation. Since we are using typescript in our project and have interfaces for all our collections, I am seeking an efficient method to achieve this.
Here is the process:
Step 1: Convert the interface:
import { ObjectId } from 'mongodb';
export interface Category {
_id: ObjectId;
date: Date;
level: string | null;
}
Step 2: Transform it into a JSON Schema
export const CategoryJSONSchema = {
required: ['_id', 'date', 'level'],
additionalProperties: false,
properties: {
_id: { bsonType: 'objectId' },
date: { bsonType: 'date' },
level: { oneOf: [{ bsonType: 'null' }, { bsonType: 'string' }] }
}
}