Creating a JSON schema for MongoDB using a TypeScript interface: a step-by-step guide

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' }] }
  }
}

Answer №1

If you're looking to create a custom ts-transformer that can generate a JSON schema, there are some tools available to help with that.

One such tool is ts-transformer-keys, which provides an example of how to use it.

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

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

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

You could even consider forking the package and modifying it to include type information for each field. This would make it easier to generate JSON or models, similar to what Prisma.io does.

Another option to explore is ts-transformer-enumerate.

Answer №2

Why not try implementing mongoose? It allows you to easily enforce your schema to adhere to a specific interface. Here's an example:

const UserSchema = new mongoose.Schema<UserInterface>({ ... });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ag-grid's onGridReady function is not functioning properly

I am trying to dynamically load ag-grid when a button is clicked, but I have encountered issues with both of my approaches. Here is my code for the first method: onBtnClick(){ this.gridOptions ={ onGridReady : function(){ console ...

Error message: MongoDB aggregation $in operator must be provided with an array as argument

Looking at the document provided, the goal is to filter out zip codes along with their corresponding res_count that are also included in the data array. Document : { "data" : [ "10451", "10458", "10467", "10461", "10462" ] } { "zipcode" : "10470", "res_c ...

Searching through JSON data without specifying a specific element name

How can I retrieve specific data from a JSON document where the element names are constantly changing? This JSON snippet was extracted from MongoDB and contains information from the FlightRadar API. I am interested in extracting only the elements ad5913d ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...

Searching for geospatial indexes on Azure CosmosDB (DocumentDB) with the Mongo API does not yield results

My Azure CosmosDB contains a collection named restaurants with a field geoJSON that specifies the location of each restaurant in geoJSON format. I am using the MongoDB API for accessing this data. Upon logging into the DB through the mongo shell, I can vi ...

How to send form group in Angular when the enter key is pressed

When I press the submit button on a form, it sends a request to the database to filter data in a grid. However, I also want the form to submit when the enter key is pressed. HTML <form [formGroup]="bmForm" (keyup.enter)="onSearchClic ...

Angular, Transforming JSON with RxJS Operators in TypeScript

Upon receiving the JSON object (Survey) from the server, it looked like this: { "id": 870, "title": "test survey", "questions": [ { "id": 871, "data": ...

It is possible that the object may be null, as indicated by TS2531 error

I was interested in using QrReader to scan a file based on [https://github.com/Musawirkhann/react_qrcode_generation_scanner This code is written in react, but I wanted to use it with tsx. However, when attempting to implement it, I encountered an error: ...

What is the purpose of having a constructor in Typescript when an interface is already used for a class?

Is it necessary to have a constructor in my class if the class already implements an interface? It seems like redundant code to me. interface PersonInterface { firstname: string; lastname: string; email: string; } class Person implements Pe ...

Consolidate records in MongoDB containing nested arrays within other nested arrays

I am attempting to tally documents based on different conditions. Below is a simplified table of texts (documents): { "teamId": "1", "stage": "0", "answeredBy": [userId_1, userId_2], "skippedBy": [userId_3], "answers": [] }, { "teamId": "1", ...

Aggregating MongoDB: Calculating unique values within an array

Looking to find the distinct tags count on all records within a mongodb query, utilizing JS. Data structure of the record: { "_id": { "$oid": "62e593aed8fd9808777225e8" }, "title": "“The world as ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

How can I nest a kendo-grid within another kendo-grid and make them both editable with on-cell click functionality?

I am facing an issue with my 2 components - trial1 (parent kendo-grid) and trial2 (child kendo-grid). Inside the template of trial1, I referenced the sub-grid component trial2. However, I am encountering an error where trial2 is not recognized inside trial ...

Creating Meta tags for Dynamic Routes in a Nuxt 3 Build

I recently encountered an issue when trying to implement dynamic OpenGraph meta tags on a dynamically generated route in Nuxt 3 (and Vue 3). I attempted to set the meta tags dynamically using Javascript, as it was the only dynamic option supported by Nuxt ...

Guide on generating a fresh Mongoose record and making modifications before finalizing and storing it

I'm currently in the process of creating a brand new Mongoose document. Here is my approach: let freshTrade = new TradeModel({ userId: userId, symbol: symbol }) My intention is to then transfer this data to another server to obtain additional inf ...

The list filter may not work properly if the search string is left blank

I am currently working on a list filtering feature that updates based on user input. As the user types, the system compares the entered text against the items in the list and displays the matching objects in an array. However, I'm facing an issue - wh ...

The module 'angular/common' was not found in the Angular 2 TypeScript

While experimenting with a sample login form in Angular 2, I encountered an issue when trying to import 'Form_Directives' as: import { FORM_DIRECTIVES } from '@angular/common'; An error was displayed stating that the angular/common m ...

Is there a way to access all routes within Nestjs, including those from all modules and controllers?

Is there a way to retrieve a list of all available routes (controller methods) with their respective HTTP verbs using Nestjs? I would like it to be displayed in a similar format: API: POST /api/v1/user GET /api/v1/user PUT /api/v ...

Best method for loading data into a new MongoDB database?

I currently have a Docker container set up locally with MongoDB and an express node server. Can anyone suggest the best method to add new data to this setup? 1) Should I utilize the command line interface (CLI)? 2) Is it better to use Mongoose for this ta ...