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

The ESLINT_NO_DEV_ERRORS flag appears to be ineffective in my Typescript project

Currently, my project involves using the following tools: Yarn Typescript Create React App ESLint Make (Makefile) Fish shell During development, I encounter ESLint errors that prevent my project from compiling. To run my project, I use make run, which es ...

Exploring the capabilities of supertest by testing endpoints in Express with NodeJS

Having trouble setting up a test environment to test my TypeScript Express Node.js endpoints. Here are the packages I've installed: jest ts-jest jest-junit supertest @types/supertest @types/jest This is how my spec file looks like: imp ...

Encountering an issue while developing a Discord bot using TypeScript

Hello, I'm currently working on creating a nick command for my discord bot in TypeScript, but I encountered an error. Here is the issue: Error: Expression expected.ts (1109) When I replace const mentionedMember = message? message.mentions.members? ...

Utilizing a Link element in conjunction with ListItem and Typescript for enhanced functionality

I am currently using material-ui version 3.5.1 My goal is to have ListItem utilize the Link component in the following manner: <ListItem component={Link} to="/some/path"> <ListItemText primary="Text" /> </ListItem> However, when I tr ...

Enhance Vue TypeScript components with custom component-level properties

In my vue2 project, I am utilizing vue-class-component along with vue-property-decorator. My goal is to implement component-level security validation for each component when it loads. I imagine implementing it with a signature like this: @Component @Secur ...

Unreliable passing of variables from Express to Jade

Currently experimenting with Node.js, Express, Jade, and MongoDB, I encountered an unusual issue related to rendering. I passed the variable "users" which is obtained from a database query like so: userProvider.findByIds(ids, function(error, users) { re ...

The 'getAllByRole' property is not found in the 'Screen' type. TS2339 error

I am currently developing a web application using ReactJs for the front end. While testing the code, I encountered the following error: TypeScript error in My_project/src/unitTestUtils.tsx(79,27): Property 'getAllByRole' does not exist on type & ...

What is the process for fetching a specific item from the database?

I have a setup with a default model to view data and a form to input it. What is the best practice for fetching the selected item of data? This is for a MERN stack project. Currently, I am using window hash to add the id to the URL and retrieve the data f ...

Ways to manage an rxjs observable reaction that may potentially have no data?

Currently, I am working with Angular2 and Ionic2 using typescript and have a requirement to manage responses from the backend service. The response may either be empty with http status 200 or it could be a json object containing an error message property ...

I am experiencing issues with my Jest unit test case for Material UI's multi select component failing

I've been working on writing a unit test case for the material UI multi select component. The code for the parent component is as follows: import {myData} from '../constant'; export const Parent = () => { const onChangeStatus= (sel ...

The specified target "TypeScriptClean" is not present within the project

I'm facing some issues in Visual Studio 2017 Professional. Despite not having any TypeScript code in my solution, I am encountering numerous TypeScript-related errors during the build process. The main error message that keeps popping up is: The targ ...

Guide on navigating to a specific step within a wizard using Vue and TypeScript

In this wizard, there are 6 steps. The last step includes a button that redirects the user back to step 4 when clicked. The user must then complete steps 5 and 6 in order to finish the wizard. step6.ts <router-link to="/stepFour" ...

Getting a date object that is three months prior to the current date in Typescript

I need to retrieve the date object that is 3 months before the current date by using the following code snippet: toDate = new Date(); fromDate = this.toDate.getMonth() - 3; The issue I am facing is that the variable fromDate only contains a number, but I ...

Bidirectional communication linking an Angular 2 component and service utilizing the power of Observables

I'm having difficulties establishing a simple connection between an Angular 2 component and service using Observable. I've been trying to achieve this, but I can't seem to get it right. Here's the scenario: My component HeroViewerCompo ...

Differentiating response.data typing on the front end in Typescript depending on the request's success status

Consider this scenario: A secure API authentication route that I am not allowed to access for viewing or editing the code returns interface AuthSuccess { token: string user: object } on response.data if the email and password provided are correct, but ...

What results can be expected from a piped file stream?

Perhaps the wording of the question may not be perfect, but here is some additional context. With GridFSBucket, I am able to store a file in MongoDB and retrieve a download stream for that file. Here's my query: If I wanted to send that file back as a ...

In Angular, dynamically updating ApexCharts series daily for real-time data visualization

I am currently working with apexchart and struggling to figure out how to properly utilize the updateseries feature. I have attempted to directly input the values but facing difficulties. HTML <apx-chart [chart]="{ type: ...

How can we ensure in ReactJS that one API call has been completed before making another one?

How can we ensure one API call is completed before making the next call in reactJS? In my componentDidMount function, I need to check the length of data. When the length is more than 4, I first want to save the data and then retrieve it. componentDidM ...

Steps to apply a decorator to a function that is not a nestjs route

NestJS Hello there! I am currently facing an issue where I need to apply a decorator to a function that is not serving as an endpoint or route. To illustrate, here is what I have in mind: class Controller { @Get('/') firstMethod() { ...

"Exploring the process of extracting data from a JSON URL using NextJS, TypeScript, and presenting the

After tirelessly searching for a solution, I found myself unable to reach a concrete conclusion. I was able to import { useRouter } from next/router and successfully parse a local JSON file, but my goal is to parse a JSON object from a URL. One example of ...