Skip to content
EventFabric CQRS Framework

Deploy Collection

The deployMongoCollection function creates or updates MongoDB collections with schema validation and indexes. It provides a declarative way to manage your database schema.

An in Depth Example

This guide also has an in depth example of a working application built with EventFabric. Combining DDD, CQRS and Event Sourcing.

Check out the In Depth Example page to learn how everything is connected and works out in a real-world application.

import { deployMongoCollection } from "@nimbus-cqrs/mongodb";
import { mongoManager } from "./mongodb.ts";

const USERS_COLLECTION = {
    name: "users",
    options: {
        validator: {
            $jsonSchema: {
                bsonType: "object",
                required: ["email", "firstName", "lastName"],
                properties: {
                    email: { bsonType: "string" },
                    firstName: { bsonType: "string" },
                    lastName: { bsonType: "string" },
                },
            },
        },
    },
    indexes: [
        { key: { email: 1 }, unique: true },
        { key: { lastName: 1, firstName: 1 } },
    ],
};

const client = await mongoManager.getClient();

await deployMongoCollection({
    mongoClient: client,
    dbName: "myDatabase",
    collectionDefinition: USERS_COLLECTION,
    allowUpdateIndexes: true,
});
ParameterTypeDescription
mongoClientMongoClientA connected MongoDB client instance
dbNamestringThe name of the database
collectionDefinitionMongoCollectionDefinitionThe collection definition object
allowUpdateIndexesbooleanWhether to update indexes on existing collections

The MongoCollectionDefinition type defines the structure of a collection:

type MongoCollectionDefinition = {
    name: string;
    options?: CreateCollectionOptions;
    indexes?: IndexDescription[];
};
PropertyTypeDescription
namestringThe name of the collection
optionsCreateCollectionOptionsMongoDB collection options (validation, etc.)
indexesIndexDescription[]Array of index definitions

The function handles two scenarios:

When the collection does not exist:

  1. Creates the collection with the specified options
  2. Creates all defined indexes

When the collection already exists:

  1. Updates collection options using collMod
  2. If allowUpdateIndexes is true:
    • Creates any new indexes not present in the database
    • Drops any indexes not defined in the collection definition (except _id_)

Indexes are automatically named based on their key fields if no name is provided:

// This index will be named "email_1"
{ key: { email: 1 } }

// This index will be named "lastName_1_firstName_1"
{ key: { lastName: 1, firstName: 1 } }

// Explicit name
{ key: { email: 1 }, name: "email_unique_idx", unique: true }

Create a script to deploy all collections:

import { deployMongoCollection } from "@nimbus-cqrs/mongodb";
import { setupLogger, parseLogLevel } from "@eventfabric-cqrs/core";
import { mongoManager } from "./mongodb.ts";
import { USERS_COLLECTION } from "./collections/users.ts";
import { ORDERS_COLLECTION } from "./collections/orders.ts";

// Configure logging to see deployment progress
setupLogger({
    logLevel: parseLogLevel("info"),
});

const collections = [USERS_COLLECTION, ORDERS_COLLECTION];

const deployCollections = async () => {
    const client = await mongoManager.getClient();
    const dbName = process.env.MONGO_DB ?? "myDatabase";

    for (const collection of collections) {
        await deployMongoCollection({
            mongoClient: client,
            dbName,
            collectionDefinition: collection,
            allowUpdateIndexes: true,
        });
    }

    console.log("All collections deployed successfully");
};

deployCollections().catch(console.error);