Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
Migrate
✓ import { Migrate } from 'ts-migrate-mongoose';
✗ const Migrate = require('ts-migrate-mongoose').Migrate;
This is the primary class for programmatic migration management. Use named import for ESM. For CommonJS, access the named export from the `require` object.
IMigration
✓ import type { IMigration } from 'ts-migrate-mongoose';
✗ import { IMigration } from 'ts-migrate-mongoose';
Interface for defining migration classes. It is a type-only import; using `import { IMigration }` can lead to unnecessary bundle size or runtime errors if the type is not also a value.
runCLI
✓ import { runCLI } from 'ts-migrate-mongoose';
✗ import runCLI from 'ts-migrate-mongoose';
Provides a programmatic way to invoke the library's CLI logic directly within your application, often used for custom scripts or server startup hooks. It is a named export.
Demonstrates connecting to MongoDB using Mongoose, defining a simple TypeScript migration class by implementing `IMigration`, initializing the `Migrate` runner with basic configuration, and then programmatically running a migration's `up` method. This showcases the core API interaction for schema modifications.
import mongoose from 'mongoose';
import { Migrate, IMigration } from 'ts-migrate-mongoose';
// 1. Define your migration class implementing IMigration
class AddTimestampToUsers implements IMigration {
async up(): Promise<void> {
console.log('Running up migration: AddTimestampToUsers');
// Example: Add a 'createdAt' and 'updatedAt' field to existing user documents
await mongoose.connection.db.collection('users').updateMany(
{}, // Filter for all documents
{ $set: { createdAt: new Date(), updatedAt: new Date() } }, // Add new fields
{ upsert: false } // Do not create new documents if no match
);
console.log('Migration AddTimestampToUsers (up) completed.');
}
async down(): Promise<void> {
console.log('Running down migration: AddTimestampToUsers');
// Example: Remove the 'createdAt' and 'updatedAt' fields from user documents
await mongoose.connection.db.collection('users').updateMany(
{}, // Filter for all documents
{ $unset: { createdAt: '', updatedAt: '' } } // Remove fields
);
console.log('Migration AddTimestampToUsers (down) completed.');
}
}
async function main() {
// 2. Connect to MongoDB using Mongoose
const mongoUri = process.env.MONGO_URI ?? 'mongodb://localhost:27017/my_ts_migrate_db';
await mongoose.connect(mongoUri);
console.log('Connected to MongoDB.');
// 3. Initialize the Migrate runner with configuration
const migrator = new Migrate({
migrationsPath: './migrations', // Directory where migration files are located (e.g., compiled JS files)
uri: mongoUri,
collectionName: 'migrations_log', // Collection to track applied migrations
// Other options like `templatePath`, `compilerOptions`, etc.
});
// In a real application, you would create a migration file (e.g., `migrations/20231027120000-add-timestamp-to-users.ts`)
// and `migrator.up()` or `migrator.down()` would discover and run it.
// For this quickstart, we'll demonstrate the core logic by manually running the `up` method.
console.log('\n--- Simulating a migration UP run ---');
const tempMigrationInstance = new AddTimestampToUsers();
await tempMigrationInstance.up();
console.log('Simulated UP migration complete. (In a real scenario, this would be tracked by the migrator.)\n');
// To run all pending migrations (requires migration files in `migrationsPath`)
// await migrator.up();
// console.log('All pending migrations (up) completed.');
// To run all migrations down
// await migrator.down();
// console.log('All migrations (down) completed.');
// 4. Disconnect from MongoDB
await mongoose.disconnect();
console.log('Disconnected from MongoDB.');
}
main().catch(console.error);
ts-migrate-mongoose --version
Errors
Common errors & fixes
Error: Cannot find module 'mongoose' or Error: Cannot find module 'ts-migrate-mongoose'
One of the core runtime dependencies (mongoose or ts-migrate-mongoose itself) is not installed in your project's node_modules.
fixRun `npm install mongoose ts-migrate-mongoose` (or equivalent for pnpm/yarn) to ensure both packages are correctly installed.
Error: Node.js version X.Y.Z is not supported. This package requires Node.js >=20.
The current Node.js runtime environment is older than the minimum required version (Node.js 20.x) as specified by the package since v5.2.0.
fixUpgrade your Node.js environment to version 20 or newer. Use `nvm install 20 && nvm use 20` or similar methods.
Error: Unknown argument: --uri or Error: Unknown argument: --database
You are attempting to use CLI flags that are no longer recognized by the package, typically after upgrading to v5.0.0 which removed the `commander` dependency.
fixConsult the latest documentation for the correct CLI arguments and configuration methods. Configuration may now rely more on `migrate.json`, `migrate.ts` files, or environment variables (`process.env.MONGO_URI`).
TypeError: (0 , ts_migrate_mongoose_1.Migrate) is not a constructor
This error often indicates an incorrect import statement, module resolution issue (e.g., mixing CommonJS `require` with ESM exports), or attempting to instantiate a non-constructor.
fixEnsure you are using the correct import syntax for your module environment: `import { Migrate } from 'ts-migrate-mongoose';` for ESM, or `const { Migrate } = require('ts-migrate-mongoose');` for CommonJS, followed by `new Migrate(...)`. Audit
Dependencies
mongooserequiredCore ORM dependency for which migrations are managed. This is a required peer dependency.
@nestjs/commonoptionalPeer dependency specifically for integrations with the NestJS framework, as shown in examples and test setups.