Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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' }] }
  }
}
like image 532
DauleDK Avatar asked Oct 21 '25 09:10

DauleDK


1 Answers

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

like image 88
Medet Tleukabiluly Avatar answered Oct 23 '25 00:10

Medet Tleukabiluly