Skip to main content
Migrations in Orionjs are used to perform data transformations and schema updates on existing data. They run automatically via a background job and track completion state to ensure each migration runs only once.

Installation

Structure and Naming

  • Use @MigrationService() decorator from @orion-js/migrations
  • Each migration should be a separate class
  • Follow naming convention: Migrate{Entity}{Action}.v{Version} (e.g., MigrateUsersPlanType.v1)
  • Implement a runMigration() method that performs the migration logic
  • Version suffix (.v1, .v2) allows re-running modified migrations
  • Put migrations in app/{component}/migrations/Migrate{Entity}{Action}/index.ts

Best Practices

  • Idempotency: Design migrations to be safely re-runnable when possible
  • Progress logging: Log progress every N documents for long-running migrations
  • Query optimization: Only fetch documents that need updating (use $exists: false or similar filters)
  • Batch processing: Process documents in a cursor loop, not loading all into memory
  • Direct collection access: Migrations are the exception where direct collection access is allowed
  • Use useMongoTransactions: false unless you specifically need transaction support
  • Use dependency injection to leverage existing services for business logic
  • Define local interfaces for document shapes to avoid tight coupling with schema changes

Complete Example

Simple Migration Example

For simple field additions or transformations without external dependencies:

Loading Migrations

Migrations must be registered using loadMigrations() to enable automatic execution:

How Migrations Run

  • Migrations are executed by a background job that polls every 30 seconds
  • Only one migration runs at a time, in the order they are registered
  • Completed migrations are tracked in the orionjs.migrations collection
  • The migration name serves as the unique identifier for tracking completion
  • A lock prevents concurrent migration execution across multiple server instances

MongoDB Transactions

For operations that need to be atomic, you can use MongoDB transactions:

Long-Running Migrations

For migrations that take a long time, extend the lock time:

Disabling Automatic Execution

If you want to manually control when migrations run:
Then manually trigger migrations:

When to Create a New Migration Version

Create a new version (.v2, .v3, etc.) when:
  • The original migration logic had a bug that needs fixing
  • You need to re-run a migration with modified logic
  • The migration name must change to run again (completed names are tracked)