@coodex.ai/mongo-migrations
v0.1.6
Published
Tool to manage migrations in MongoDB
Maintainers
Readme
Mongo Migrations
Tool to manage migrations in MongoDB.
Installation
npm install @coodex.ai/mongo-migrationsCreating Migrations
Create a new migration file using the CLI command:
npx mongo-migrations create <migration-name>Or if installed globally:
npm install -g @coodex.ai/mongo-migrations
mongo-migrations create add-user-indexesThis will create a new migration file in the src/migrations directory (or the path specified by MIGRATIONS_PATH environment variable) with the following structure:
import { Db } from 'mongodb';
export async function up(db: Db): Promise<void> {
// Implement your migration here
// Example:
// await db.collection('users').createIndex({ email: 1 }, { unique: true });
}
export async function down(db: Db): Promise<void> {
// Implement rollback here
// Example:
// await db.collection('users').dropIndex('email_1');
}Usage
const { MigrationManager } = require('@coodex.ai/mongo-migrations');
// Option 1: Using environment variables (MONGO_URI and DB_NAME)
const manager = new MigrationManager({
migrationsPath: './src/migrations'
});
// Option 2: Explicit configuration
const manager = new MigrationManager({
uri: 'mongodb://localhost:27017',
database: 'my-database',
migrationsPath: './src/migrations'
});
// Option 3: Mix of both (explicit config takes precedence)
const manager = new MigrationManager({
database: 'my-database', // explicit
// uri will use MONGO_URI from env
migrationsPath: './src/migrations'
});
// Run pending migrations
await manager.up();CLI Command
You can also run migrations using the CLI command. The CLI automatically loads variables from .env file:
# Option 1: Using .env file (recommended)
# Create a .env file in your project root:
# MONGO_URI=mongodb://localhost:27017
# DB_NAME=my-database
# MIGRATIONS_PATH=./src/migrations # Optional
npx mongo-migrations up
# Option 2: Using environment variables
export MONGO_URI="mongodb://localhost:27017"
export DB_NAME="my-database"
export MIGRATIONS_PATH="./src/migrations" # Optional, defaults to ./src/migrations
npx mongo-migrations upOr if installed globally:
npm install -g @coodex.ai/mongo-migrations
mongo-migrations upEnvironment Variables
MONGO_URI- MongoDB connection string (required for CLI)DB_NAME- Database name (required for CLI)MIGRATIONS_PATH- Path to migrations directory (defaults to./src/migrations)
Development
# Install dependencies
npm install
# Compile TypeScript
npm run build
# Run tests
npm test
# Watch mode for development
npm run watchPublishing
# Build before publishing
npm run build
# Publish to npm
npm publishLicense
GPL-3.0
