Mongoose Migration Framework
migrate-mongoose is a robust migration framework designed for Node.js projects that utilize Mongoose for MongoDB interaction. It's currently in version 4.0.0, having recently released a major update. A key differentiator is its approach to storing migration state directly within MongoDB, rather than relying on a local file system, making it well-suited for Platform as a Service (PaaS) deployments like Heroku where ephemeral file systems are common. The framework provides features such as access to Mongoose models directly within migration files, support for promises or standard callbacks, flexible configuration via files or environment variables (including `.env` support), and tools for managing (pruning) migration files. It tracks migration status globally in the database, simplifying deployment and ensuring consistency across environments. Release cadence appears to be driven by feature additions, Mongoose updates, or necessary dependency changes rather than a fixed schedule.
Common errors
-
Error: Missing required argument: dbConnectionUri
cause The `--dbConnectionUri` option was not provided, nor was `MIGRATE_dbConnectionUri` set as an environment variable or in a `.env` file.fixProvide the database connection URI using `npx migrate <command> --dbConnectionUri <uri>` or by setting `export MIGRATE_dbConnectionUri='<uri>'` (or in a `.env` file). -
Error: There are no migrations to run.
cause You tried to run `migrate up`, but all local migration files already have a corresponding 'up' entry in the database, meaning they've all been applied.fixThis is often not an error but an informational message. If you expect migrations to run, check if new migration files exist in your `migrations` directory or if they've already been applied. -
Error: migration 'your_migration_name' not found
cause The migration name provided to `migrate down` does not correspond to an existing local migration file or a recorded migration in the database.fixEnsure the migration name is correct and the corresponding migration file exists. Use `npx migrate list` to see available migrations.
Warnings
- breaking Version 4.0.0 removed Babel support. Projects relying on older Babel configurations for migration files may need to update their Node.js environment or transpile migrations separately if using very old ES features not natively supported by your Node.js version.
- gotcha Migration state is stored directly in MongoDB, which is a core feature but can be a surprise for users accustomed to file-based migration trackers. This is critical for PaaS environments, but means your database needs to be accessible.
- gotcha The `down` command requires a specific migration name to roll back to, unlike `up` which can run all pending migrations by default. Omitting the migration name for `down` will result in an error.
- gotcha Configuration options like `--dbConnectionUri` can be set via environment variables prefixed with `MIGRATE_` (e.g., `MIGRATE_dbConnectionUri`) or through a `.env` file. These take precedence over default options.
Install
-
npm install migrate-mongoose -
yarn add migrate-mongoose -
pnpm add migrate-mongoose
Imports
- mongoose
const mongoose = require('mongoose');import mongoose from 'mongoose';
- run
import { run } from 'migrate-mongoose';require('migrate-mongoose'); // This primarily executes the CLI entry point - MigrationFunction
/** @typedef {import('mongoose').Connection} MongooseConnection */ /** @typedef {(db: any, client: MongooseConnection) => Promise<void>} MigrationFunction */
Quickstart
npm install migrate-mongoose
# Configure database URI via .env file
echo "MIGRATE_dbConnectionUri=mongodb://localhost:27017/my_app_db" > .env
# Or, set as environment variable directly (e.g., in a CI/CD pipeline)
# export MIGRATE_dbConnectionUri=mongodb://localhost:27017/my_app_db
# Create a new migration file
npx migrate create add_users_collection
# This will generate a file like './migrations/123456789-add_users_collection.js'
# Edit the migration file (example content for add_users_collection.js):
/*
module.exports = {
async up(db, client) {
const users = client.connection.db.collection('users');
await users.createIndex({ email: 1 }, { unique: true });
console.log('Users collection index created.');
},
async down(db, client) {
const users = client.connection.db.collection('users');
await users.dropIndex('email_1'); // Use the actual index name from MongoDB
console.log('Users collection index dropped.');
}
};
*/
# Run pending migrations (applies 'up' function)
npx migrate up
# List all migrations and their status
npx migrate list