Registry / database / ts-migrate-mongoose

ts-migrate-mongoose

JSON →
library5.3.2jsnpmunverified

ts-migrate-mongoose is a robust migration framework for Mongoose, specifically designed for managing database schema changes in MongoDB with TypeScript. The current stable version is 5.3.2, with an active and responsive release cadence, frequently publishing minor and patch updates to introduce new features, security enhancements, and compatibility fixes. Key differentiators include its ability to store migration state directly within MongoDB, flexible configuration options via `migrate.json`, `migrate.ts`, or `.env` files, direct utilization of Mongoose models within migrations, comprehensive support for async/await, and versatile execution options through both CLI and programmatic interfaces. It also supports pruning, syncing, custom templates, single migration execution, and is compatible with both ESM and CommonJS module systems across various Node.js frameworks.

npm install ts-migrate-mongoose
INSTALL
IMPORT
SIG · TS-MIGRATE-MONGOOS
T
ts-migrate-mongoose
databasejavascriptv5.3.2
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
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
musl
node 18–226 runs
build_error
glibc
node 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
Debug
Known issues
breakingVersion 5.0.0 removed direct dependencies on `commander`, `dotenv`, and `@inquirer/prompts`. Users must now adapt to using Node.js built-ins for CLI argument parsing and environment variable loading, or provide their own wrappers.
fix
Review existing CLI scripts and configuration. Replace usages of the removed libraries with standard Node.js mechanisms like `process.argv` and `process.env`. If using `migrate.json` or `migrate.ts` for configuration, ensure compatibility.
affects: >=5.0.0
breakingNode.js 18.x support was explicitly removed in version 5.2.0. The package now requires Node.js version 20.x or higher, as stated in the `engines` field, for optimal functionality and full test matrix coverage.
fix
Upgrade your Node.js environment to a supported version (20.x, 22.x, 24.x, etc.). Using a Node.js version manager like `nvm` (`nvm install 20 && nvm use 20`) is recommended.
affects: >=5.2.0
gotchaIt is critical to install `mongoose` as a peer dependency alongside `ts-migrate-mongoose`. Failure to do so will result in `module not found` errors at runtime when the library attempts to interact with Mongoose.
fix
Ensure `mongoose` is installed in your project's dependencies: `npm install mongoose` or `pnpm add mongoose` or `yarn add mongoose`.
affects: >=4.0.0
gotchaVersion 5.3.0 introduced significant security enhancements, including the rejection of traversal names in paths and improved error cause chaining. While not a direct breaking change, it's a strong recommendation to upgrade to benefit from these hardening measures and ensure the most secure operation.
fix
Upgrade to the latest `ts-migrate-mongoose` version (`npm install ts-migrate-mongoose@latest`) to incorporate the latest security patches and improvements.
affects: >=5.3.0
gotchaWhen utilizing alias imports (e.g., `@/components`) within your project's migration files, `ts-migrate-mongoose` requires your `tsconfig.json` paths to be correctly configured to resolve these aliases during migration execution, especially if running compiled JavaScript files.
fix
Verify that your `tsconfig.json` includes `paths` mappings for any aliases used within your migration source files. This may necessitate additional configuration or a custom compilation step for migrations.
affects: *
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.
fix
Run `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.
fix
Upgrade 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.
fix
Consult 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.
fix
Ensure 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(...)`.
Upgrade
Version history
5.3.2latest on npm
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.
Agent activity
13 hits · last 30 days
node
12
OpenAI (training)
1
Resources