How to generate a MongoDB JSON Schema from a typescript interface?

1.4k views Asked by At

My objective is to improve data quality in our MongoDB db - by using JSON Schema validation. We are using typescript in our project, and have interfaces for all our collections.

So I'm basically looking for an effective way of;

Converting this interface:

import { ObjectId } from 'mongodb';

export interface Category {
  _id: ObjectId;
  date: Date;
  level: string | null;
}

Into this JSON Schema

export const CategoryJSONSchema = {
  required: ['_id', 'date', 'level'],
  additionalProperties: false,
  properties: {
    _id: { bsonType: 'objectId' },
    date: { bsonType: 'date' },
    level: { oneOf: [{ bsonType: 'null' }, { bsonType: 'string' }] }
  }
}
2

There are 2 answers

1
Giusseppe On

Have you considered using mongoose? You can force your schema to comply with an interface. For example:

const CategorySchema = new mongoose.Schema<CategoryInterface>({ ... });
0
Medet Tleukabiluly On

You need a custom ts-transformer, to generate json schema.

Here's a ts-transformer-keys example

import { keys } from 'ts-transformer-keys';

interface Props {
  id: string;
  name: string;
  age: number;
}
const keysOfProps = keys<Props>();

console.log(keysOfProps); // ['id', 'name', 'age']

I would fork the package, tweak it so that it also exposes types of field. Then having type information, it would be easy to generate json or model. Similar to what Prisma.io does.

Also there is ts-transformer-enumerate