Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/abejarano/ts-mongo-criteria/llms.txt

Use this file to discover all available pages before exploring further.

@abejarano/ts-mongodb-criteria ships with a ts-mongo CLI that wraps migrate-mongo — a battle-tested migration runner for MongoDB. This lets you version-control index changes, collection renames, and document transformations right alongside your TypeScript application code, with a migrate-mongo-config.js file that is pre-wired to the same environment variables used by MongoClientFactory.

Setup

Installing the CLI

The ts-mongo binary is included when you install the package — no separate install step is required:
npm install @abejarano/ts-mongodb-criteria
# or
yarn add @abejarano/ts-mongodb-criteria
# or
bun add @abejarano/ts-mongodb-criteria
After installation, ts-mongo is available as a local binary through your package manager’s script runner.

Environment variables

The migration config reads the same environment variables used by MongoClientFactory. You can provide either a full connection string or the individual components:
# Option A — full connection string
MONGO_URI=mongodb+srv://user:pass@cluster.mongodb.net
MONGO_DB=myapp_production

# Option B — individual components (the library assembles the URI)
MONGO_USER=myapp
MONGO_PASS=secretpassword
MONGO_SERVER=cluster0.abc123.mongodb.net
MONGO_DB=myapp_production

# Local development example
MONGO_USER=admin
MONGO_PASS=password
MONGO_SERVER=localhost:27017
MONGO_DB=myapp_dev
Add these to your .env file. If MONGO_URI is set, it takes precedence over the individual variables.

Config file

The CLI uses migrate-mongo-config.js at the root of your project. Running ts-mongo migrate:init creates this file automatically. It stores migration state in a migrations collection inside your database.
// migrate-mongo-config.js (example — generated by ts-mongo migrate:init)
const config = {
  mongodb: {
    url: process.env.MONGO_URI,
    databaseName: process.env.MONGO_DB,
    options: {
      useNewUrlParser: true,
    },
  },
  migrationsDir: "migrations",
  changelogCollectionName: "migrations",
  migrationFileExtension: ".js",
  useFileHash: false,
  moduleSystem: "commonjs",
};

module.exports = config;
When your package.json contains "type": "module", running ts-mongo migrate:init automatically appends the -m esm flag to the underlying migrate-mongo init call. This tells migrate-mongo to generate an ESM-compatible config. Refer to the migrate-mongo documentation for the exact generated output.

Commands reference

# Create a new migration file
# npm script
bun run migrate:create add-users-email-index

# Direct CLI
npx ts-mongo migrate:create add-users-email-index
Add these as scripts in your package.json for convenience:
{
  "scripts": {
    "migrate:create": "ts-mongo migrate:create",
    "migrate:up":     "ts-mongo migrate:up",
    "migrate:down":   "ts-mongo migrate:down",
    "migrate:status": "ts-mongo migrate:status"
  }
}

migrate:create <name>

Creates a new timestamped migration file inside the migrations/ directory:
migrations/
  20240115120000-add-users-email-index.js
The name argument becomes part of the filename and is used to identify the migration in the status output. Use a short, descriptive slug.

migrate:up

Reads the migrations changelog collection to determine which files have not yet been applied, then runs them in chronological order. Each migration’s up function receives the native Db object from the MongoDB driver.

migrate:down

Rolls back the last applied migration by calling its down function. Run it multiple times to roll back further.

migrate:status

Prints a table of all migration files and whether each one has been applied (up) or is pending:
┌─────────────────────────────────────────────────────┬──────────────┐
│ Filename                                            │ Applied At   │
├─────────────────────────────────────────────────────┼──────────────┤
│ 20240101000000-init-users-index.js                  │ 2024-01-01   │
│ 20240115120000-add-users-email-index.js             │ 2024-01-15   │
│ 20240120090000-add-products-text-index.js           │ pending      │
└─────────────────────────────────────────────────────┴──────────────┘

Example migration file

The following migration adds a unique index on users.email in up, and drops it again in down. The db argument is the raw Db instance from the MongoDB Node.js driver.
// migrations/20240115120000-add-users-email-index.js

module.exports = {
  /**
   * Apply the migration — runs when `migrate:up` is executed.
   * @param {import('mongodb').Db} db
   */
  async up(db) {
    await db.collection("users").createIndex(
      { email: 1 },
      { unique: true, name: "users_email_unique" }
    );
  },

  /**
   * Revert the migration — runs when `migrate:down` is executed.
   * @param {import('mongodb').Db} db
   */
  async down(db) {
    await db.collection("users").dropIndex("users_email_unique");
  },
};
A more involved example that adds a compound index and a TTL index in a single migration:
// migrations/20240120090000-add-orders-indexes.js

module.exports = {
  async up(db) {
    const orders = db.collection("orders");

    // Compound index for status + date queries
    await orders.createIndex(
      { userId: 1, status: 1, createdAt: -1 },
      { name: "orders_user_status_date" }
    );

    // TTL index — auto-delete soft-deleted orders after 90 days
    await orders.createIndex(
      { deletedAt: 1 },
      { expireAfterSeconds: 60 * 60 * 24 * 90, name: "orders_ttl_deleted" }
    );
  },

  async down(db) {
    const orders = db.collection("orders");
    await orders.dropIndex("orders_user_status_date");
    await orders.dropIndex("orders_ttl_deleted");
  },
};
Migrations are app-specific, not library-specific. If you consume @abejarano/ts-mongodb-criteria as a dependency in your own project, you need to replicate this setup in your own repository: copy migrate-mongo-config.js to your project root, create a migrations/ directory, and add the migrate:* npm scripts. The library’s own migrations folder should not be used for your application migrations.
Running ts-mongo migrate:init in a project where package.json sets "type": "module" passes -m esm to migrate-mongo init automatically, producing an ESM-compatible config. If you hand-edit the config file after the fact, make sure the module format matches what Node.js expects for .js files in your project.

Build docs developers (and LLMs) love