migrate-mongo

raw JSON →
14.0.7 verified Sat Apr 25 auth: no javascript

A database migration tool for MongoDB in Node.js, currently at version 14.0.7. Supports MongoDB drivers 4.x through 7.x and requires Node.js >=20.0.0. It provides CLI commands (init, create, up, down, status) and programmatic API. Key differentiators: lightweight, lock-based concurrency, checksum validation, and support for both CommonJS and ESM module systems. Common pitfalls include incorrect configuration file exports, missing peer dependency mongodb, and improper use of up/down functions in migration files.

error Error: Cannot find module 'migrate-mongo'
cause migrate-mongo not installed or not in PATH (global install missing).
fix
Install locally with 'npm install migrate-mongo --save-dev' or globally with 'npm install -g migrate-mongo'.
error Error: Collection not found: changelog
cause Migration database not initialized; need to run 'migrate-mongo up' first.
fix
Run 'migrate-mongo up' to apply pending migrations and create changelog collection.
error MongoParseError: options usecreateindex, usefindandmodify are not supported
cause Deprecated options passed to MongoDB driver.
fix
Remove 'useCreateIndex' and 'useFindAndModify' from config; they are no longer needed.
breaking Node.js >=20.0.0 required as of v14. Older versions will fail.
fix Upgrade Node.js to 20 or later.
breaking MongoDB driver versions below 4.4 are not supported; driver 7.x requires specific connection options.
fix Install mongodb driver ^4.4.1 || ^5.0.0 || ^6.0.0 || ^7.0.0.
deprecated useNewUrlParser and useUnifiedTopology options are deprecated in MongoDB driver 4.x+.
fix Remove these options from config; they are now default.
gotcha If using ESM (moduleSystem: 'esm'), migration files must use .mjs extension or set "type": "module" in package.json.
fix Use .mjs extension or configure package.json appropriately.
npm install migrate-mongo
yarn add migrate-mongo
pnpm add migrate-mongo

Shows full workflow: install, init, create migration file with up/down functions, run via CLI or programmatic API.

// 1. Install: npm install migrate-mongo mongodb
// 2. Initialize project: npx migrate-mongo init
// 3. Configure 'migrate-mongo-config.js' with your MongoDB URL and database name.
// 4. Create a migration: npx migrate-mongo create add-users
// 5. Edit the generated file in migrations/:

export async function up(db, client) {
  await db.collection('users').insertOne({ name: 'John', email: 'john@example.com' });
}
export async function down(db, client) {
  await db.collection('users').deleteOne({ name: 'John' });
}

// 6. Run migrations: npx migrate-mongo up
// Programmatic usage:
import { up, down, config } from 'migrate-mongo';
const migrationConfig = await config.read();
await up(migrationConfig);
// or await down(migrationConfig);