MongoDB exporter documentation

Overview

MongoDBExporter Convert the JSON Schema generated by schema-dsl into MongoDB's $jsonSchema validation format, which can be directly used for document validation when creating a collection.

Core functions

  • ✅ Convert to MongoDB $jsonSchema format
  • ✅ Automatic mapping type is BSON type
  • ✅ Keep all constraints
  • ✅ Generate createCollection command
  • ✅Support strict/loose validation mode

quick start

import { s, exporters } from 'schema-dsl/pure';

// 1. Define Schema
const userSchema = s({
  username: 'string:3-32!',
  email: 'email!',
  age: 'number:18-120'
});

// 2. Create exporter
const exporter = new exporters.MongoDBExporter();

// 3. Export to MongoDB Schema
const mongoSchema = exporter.export(userSchema);
console.log(JSON.stringify(mongoSchema, null, 2));

Output:

{
  "$jsonSchema": {
    "bsonType": "object",
    "required": ["username", "email"],
    "properties": {
      "username": {
        "bsonType": "string",
        "minLength": 3,
        "maxLength": 32
      },
      "email": {
        "bsonType": "string"
      },
      "age": {
        "bsonType": "double",
        "minimum": 18,
        "maximum": 120
      }
    }
  }
}

API reference

Constructor

new MongoDBExporter(options)

Parameters:

Parametertypedefault valueDescription
options.strictbooleanfalseWhether to use strict validation mode

method

export(jsonSchema)

Convert JSON Schema to MongoDB Validation Schema.

const mongoSchema = exporter.export(jsonSchema);

Parameters:

  • jsonSchema (Object): JSON Schema object generated by schema-dsl

Return Value:

  • Object: MongoDB authentication object containing $jsonSchema

generateCreateCommand(collectionName, jsonSchema)

Generate createCollection command object.

const command = exporter.generateCreateCommand('users', userSchema);

Parameters:

  • collectionName (string): collection name
  • jsonSchema (Object): JSON Schema object

Return Value:

{
  collectionName: 'users',
  options: {
    validator: { $jsonSchema: {...} },
    validationLevel: 'moderate', // or 'strict'
    validationAction: 'error'
  }
}

generateCommand(collectionName, jsonSchema)

Generate an executable MongoDB command string.

const commandStr = exporter.generateCommand('users', userSchema);
console.log(commandStr);

Output:

db.createCollection("users", {
  "validator": {
    "$jsonSchema": {
      "bsonType": "object",
      ...
    }
  },
  "validationLevel": "moderate",
  "validationAction": "error"
})

MongoDBExporter.export(jsonSchema) (static method)

Fast export without instantiation.

const mongoSchema = exporters.MongoDBExporter.export(userSchema);

Configuration options

Authentication mode

modelDescription
strict: false (default)validationLevel: 'moderate' - ​​Validates only fields involved in insert and update operations
strict: truevalidationLevel: 'strict' - ​​Validates all insert and update operations
// strict mode
const strictExporter = new exporters.MongoDBExporter({ strict: true });

Complete example

User set validation

import { s, exporters } from 'schema-dsl/pure';

//Define complex user Schema
const userSchema = s({
  _id: 'string!',
  username: s('string:3-32!').pattern(/^[a-zA-Z0-9_]+$/)
    .label('username'),
  email: s('email!').label('mailbox'),
  profile: {
    bio: 'string:500',
    avatar: 'url'
  },
  status: 'active|inactive|banned',
  createdAt: 'datetime!'
});

// Export and generate commands
const exporter = new exporters.MongoDBExporter({ strict: true });
const command = exporter.generateCommand('users', userSchema);

console.log(command);

Used in MongoDB

import { MongoClient } from 'mongodb';

async function createValidatedCollection() {
  const client = new MongoClient('mongodb://localhost:27017');
  await client.connect();

  const db = client.db('myapp');

  // Get validation Schema
  const exporter = new exporters.MongoDBExporter({ strict: true });
  const { options } = exporter.generateCreateCommand('users', userSchema);

  //Create a collection with validation
  await db.createCollection('users', options);

  console.log('Collection created successfully, document validation enabled');
}

type mapping

JSON Schema typeMongoDB BSON type
stringstring
numberdouble
integerint
booleanbool
objectobject
arrayarray
nullnull

constraint mapping

JSON Schema constraintsMongoDB constraints
minLengthminLength
maxLengthmaxLength
minimumminimum
maximummaximum
patternpattern
enumenum
minItemsminItems
maxItemsmaxItems

Export restrictions

⚠️ IMPORTANT: Not all schema-dsl features can be exported to a database schema.

Exported features not supported:

  • ❌ Conditional validation logic (s.match(), s.if())
  • ❌ Custom validator (.custom())
  • ❌ Complex JSON Schema keywords (allOf, anyOf, oneOf)
  • ❌ Custom error message (.messages())

Detailed instructions: Please read Export restrictions document



Corresponding sample file

Example entry: mongodb-exporter.ts Description: Covers $jsonSchema export, generateCreateCommand() and generateCommand(), corresponding to the validation set creation scenario in the document.