Compile MongoDB JSON Schema to TypeScript typings. This package connects to your MongoDB server, retrieves any stored JSON Schema validators, and compiles them into TypeScript typings.
For more information about MongoDB schema validation, see:
MongoDB Schema Validation and MongoDB $jsonSchema operator
Written in TypeScript and includes type definitions.
- Can be used as CLI or programmatically
- Works with vanilla JavaScript and TypeScript
- Adheres to Semantic Versioning
- CLI output is formatted with Prettier, adhering to project format options
# Yarn:
yarn add -D bson-schema-to-typescript
# NPM:
npm install bson-schema-to-typescript --save-devCreate a bson2ts.json configuration file in the root of your project to modify
the configuration defaults. It is optional to provide a configuration file.
The default configuration is:
{
"uri": "mongodb://localhost:27017",
"database": "",
"out": "src/__generated__",
"bannerComment": [
"/* eslint-disable */",
"",
"/**",
"* This file was automatically generated by bson-schema-to-typescript.",
"* https://www.npmjs.com/package/bson-schema-to-typescript",
"*",
"* Do not modify it by hand. Instead, modify the MongoDB $jsonSchema validator,",
"* and run bson2ts to regenerate this file.",
"*/"
],
"enableConstEnums": true,
"ignoreMinAndMaxItems": false,
"strictIndexSignatures": false,
"unknownAny": true
}The bson2ts CLI connects to the MongoDB server using the connection string
provided by the uri configuration option, and the database name provided by
the database configuration option.
If the uri or database configuration options start with a $ (dollar sign),
they are treated as environment variables and will be expanded.
For example, consider this configuration:
{
"uri": "mongodb://localhost:27017",
"database": "$MONGODB_DATABASE"
}In this case uri will be used as-is (eg. mongodb://localhost:27017) but
database will be use the MONGODB_DATABASE environment variable of your
system (eg. what ever process.env.MONGODB_DATABASE is set to).
In this case, uri will be used as-is (e.g. mongodb://localhost:27017), but
database will use the MONGODB_DATABASE environment variable of your system
(e.g. whatever process.env.MONGODB_DATABASE is set to).
Generate typings for each MongoDB collection.
Using npx:
npx bson-schema-to-typescriptOr add a script to package.json:
{
"scripts": {
"generate-types": "bson2ts"
}
}
Then run `yarn generate-types` or `npm run generate-types`Once you have generated the types, you can implement them like this:
import { Db } from "mongodb";
import { UserDoc } from "./__generated__/UserDoc";
import { PostDoc } from "./__generated__/PostDoc";
export function collections(db: Db) {
return {
users: db.collection<UserDoc>("users"),
posts: db.collection<PostDoc>("posts"),
};
}import {
compileBSON,
getCollectionSchema,
getDatabaseSchemas,
} from "bson-schema-to-typescript";