Using Typescript with MongoDB's JSON schema

Exploring the usage of MongoDB's $jsonschema validator with npm's json-schema-to-typescript has me intrigued. However, I've noticed that MongoDB utilizes bsontype instead of type, which may introduce additional differences that are currently unknown to me. While I could opt for a JSON schema validator like ajv instead of MongoDB's validator, implementing this validator at every point where data is inserted or updated seems cumbersome. Is there a solution that allows me to leverage MongoDB jsonschema while also generating interfaces from it? Ideally, I'd like to avoid relying on mongoose and ORMs.

Answer №1

One potential solution is to extract the BSON schema from mongodb and convert it into a "regular" JSON schema since generating typescript interface specs dynamically may not be a standard practice. The key focus here lies in mapping BSON types to equivalent JSON types.

db = db.getSiblingDB("testX");

function convertBSONtoJSON(holder, spot, value) {
    if(value == null) {
        return;
    }
    if(Array.isArray(value)) { 
        for(var jj = 0; jj < value.length; jj++) {
            convertBSONtoJSON(value, jj, value[jj]);
        }
    } else if(typeof value == "object") {
        processObject(value);
    } else {
        if(spot == 'bsonType') {
            if(value == 'int' || value == 'long') {
                holder['type'] = 'integer';
            } else if(value == 'date') {
                holder['type'] = "string";
                holder['format'] = "date-time";
            } else if(value == 'decimal') {
                holder['type'] = "string";
                holder['format'] = "decimal";
            } else {
                holder['type'] = value;
            }
            delete holder['bsonType']
        }
    }
}

function processObject(obj) {
    Object.keys(obj).forEach(function(k) {
        convertBSONtoJSON(obj, k, obj[k]);
    });
}

var collectionInfo = db.getCollectionInfos( { name: "myColl" } );
if(collectionInfo.length == 1) {
    validationExpr = collectionInfo[0].options.validator;
    if(validationExpr != undefined) {
        processObject(validationExpr);
        print(validationExpr);
    }
}

A more innovative approach could involve introducing flexible type handling capabilities in json2ts. This would enable seamless conversion of unknown types like date, decimal, etc., by utilizing a function to provide the necessary type definitions for generating complete interfaces.

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

Is there a method to prevent explicitly passing the context of "this"?

Currently, I am in the process of developing a new product and have set up both back-end and front-end projects. For the front-end, I opted to use Angular framework with Typescript. As a newcomer to this language (just a few days old), I have encountered a ...

Errors encountered when using TypeScript with destructured variables and props not being recognized

I have a function that returns data. The object is structured with properties such as headerMenu, page, content, and footer. These properties are defined in DataProps interface. When I try to destructure the data object using the line: const { headerMenu, ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

In Typescript, it mandates that a string value must be one of the values within the object

There is a constant declaration mentioned below: export const Actions = { VIEW: 'view', EDIT: 'edit', }; Imagine there's a function like this: // Ensuring that the action variable below is always a string with value either ...

What circumstances allow @Inject to be optional in Angular?

My Angular service is simple yet causing errors. Here's the code snippet: // service.ts export class SimpleService { // ... } // component.ts @Component({ selector: 'my-component', templateUrl: 'components/mycomp/mycomp.ht ...

The MatInput value will only display after the page is reloaded or refreshed

After refreshing the page, a matInput field displays a value or result that was previously hidden. https://i.stack.imgur.com/q9LQI.png By selecting or highlighting within the matInput, the value or result becomes visible. https://i.stack.imgur.com/SqaLA.p ...

Getting values from a list within a JSON object using Python and MongoDB - step by step guide

My MongoDB database has the following structure: "addr1": { "hostname": { "-name": "x" }, "os": { "-version": "x", "-acc": "x" }, "ports":{ "PORTNUMY" : { "service": "x", "version": "x" }, "PORTNUMX" : { "service": "s", "ver ...

Exploring Data in MongoDB

Is it possible to handle undefined populated fields in a MongoDB pipeline query without omitting the entire row? const pipeline = [ { $unwind: "$wholesaler" }, { $lookup: { from: "serviceproviders", localField: "serviceProvider", ...

Transform the data prior to sending it back as an observable

I am fairly new to Angular 2 and the idea of Observables. However, what I am trying to accomplish should be quite simple for experienced experts :) Here's the situation: I have a component where I have subscribed to an observable coming from a servic ...

Enhancing TypeScript Data Objects

I'm looking to expand a data object in TypeScript by introducing new fields. Although I know it's a common practice in JavaScript, I'm struggling to get it to compile without making bar optional in the provided snippet. I am interested in f ...

Configuring relative file paths within the folders in tsconfig.json

In my project, I have set up a root folder named "TypescriptProgramming" which contains the tsconfig.json file. Inside this root folder, there is another folder called "chapter1" that further includes a folder named "minfunction". The minfunction folder ho ...

Steps to access email template through an Excel web add-in

Currently, I am developing a new addin that aims to extract data from Excel and insert it into a word document. The final step would be attaching this document to an email in Outlook. While I have managed to achieve this using Power Automate, I prefer to ...

JavaScript web developer encounters an issue with MongoDb and Mongoose findOneAndUpdate method, as it unexpectedly returns undefined

I've been attempting to update an item in my mongodb database, but I'm encountering issues as the error keyword is being set to undefined. It's possible that I am making a mistake somewhere. Here's the code for the update function: rou ...

struggling to locate the data stored in MongoDB collections

In the process of developing a web app with node/express/mongodb and utilizing mongoose, I made a directory in my project named data, within which there is another folder called db. data db When starting mongo, I specify the --dbpath parameter to poin ...

Identify when the user ceases typing in Angular 2

I am currently working on implementing a feature that detects whether the user is typing or not. I need to determine when the user has stopped typing for at least 3 seconds in order to perform certain actions. I have successfully detected when the user sta ...

After successfully logging in, the deployed server encounters an Error 503 and shuts down. However, on the development environment, everything runs smoothly as

I am currently in the process of developing an application using NET 6 LTS and Angular 14. Everything runs smoothly on my development environment with IIS express. However, once I deploy the application (release version) on Windows 2019 with IIS 10, I enco ...

What sets Angular2 RxJs Observables apart: filtering compared to mapping?

When it comes to manipulating a stream in a rxjs Observable, the Filter and Map functions both appear to serve similar purposes. Through experimentation and examples, they seem to have the same functionality. What distinguishes these two functions from ea ...

Compiler fails to recognize Type Guard

I seem to be experiencing an issue with the Typescript compiler in this particular case, despite my belief that there shouldn't be any problem type Car = { isOn: boolean name: string } function doSomething(key: keyof Car, value: string | boolean ...

Enhance the capabilities of MongoDB by executing the command "mongod --upgrade"

Considering upgrading my MongoDB Replica set from version 4.2 to 4.4. I have come across conflicting information regarding the need to use the "mongod --upgrade" command after replacing the binaries with the new versions. Some sources mention it as a nece ...

Why do certain HTML elements fail to display when using ngIf?

I am facing an issue with two buttons that should display differently based on the outcome of an ngIf condition. When the page is loaded for the first time, both buttons do not appear until the page is manually refreshed, even though they are supposed to w ...