TypeScript MongoDB Migration Tool

1.2.3 · active · verified Wed Apr 22

migrate-mongo-ts is a database migration tool specifically designed for MongoDB within Node.js environments, providing robust TypeScript support. As a direct fork of the widely-used `migrate-mongo` package, it adapts its functionality for modern TypeScript workflows, ensuring type safety and improved developer experience when managing database schema changes. The current stable version is 1.2.3. This tool simplifies the process of evolving MongoDB schemas by enabling developers to define discrete 'up' and 'down' migration scripts, which are then applied and rolled back via a command-line interface. Key differentiators include its explicit focus on TypeScript for configuration and migration scripts, offering strong typing for the MongoDB `Db` and `MongoClient` objects passed into migration functions. It supports common operations such as project initialization, creating new migration files, applying pending migrations, rolling back the last migration, and checking migration status, making it a comprehensive solution for maintaining database consistency across various environments. Its release cadence typically mirrors updates from its upstream `migrate-mongo` parent, incorporating TypeScript-specific enhancements.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the installation, project initialization, generated configuration, and a sample migration file structure using the CLI.

import { Db, MongoClient } from 'mongodb';

// 1. Install CLI: npm install -g migrate-mongo-ts
// 2. Initialize project:
// $ mkdir my-app-migrations
// $ cd my-app-migrations
// $ migrate-mongo-ts init

// This is an example of the generated 'migrate-mongo-config.ts':
export default {
  mongodb: {
    url: process.env.MONGO_URL ?? "mongodb://localhost:27017",
    databaseName: process.env.MONGO_DB_NAME ?? "YOURDATABASENAME",
    options: {
      useNewUrlParser: true
    }
  },
  migrationsDir: "migrations",
  changelogCollectionName: "changelog"
};

// 3. Create a new migration:
// $ migrate-mongo-ts create initial_setup

// This is an example of the generated migration file (e.g., 'migrations/20231027090000-initial_setup.ts'):
export async function up(db: Db, client: MongoClient) {
  console.log('Running up migration: initial_setup');
  await db.collection('settings').insertOne({ version: '1.0.0', initializedAt: new Date() });
}

export async function down(db: Db, client: MongoClient) {
  console.log('Running down migration: initial_setup');
  await db.collection('settings').deleteOne({ version: '1.0.0' });
}

view raw JSON →