Mongoose Migration Framework

4.0.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

Demonstrates installation, configuration using a .env file, creating a new migration, editing the migration file with example Mongoose code, and then running and listing migrations.

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

view raw JSON →