{"id":14142,"library":"ts-migrate-mongoose","title":"TypeScript Mongoose Migration Framework","description":"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.","status":"active","version":"5.3.2","language":"javascript","source_language":"en","source_url":"https://github.com/ilovepixelart/ts-migrate-mongoose","tags":["javascript","backend","migrate","migration","migrations","mongoose","mongodb","mongo","schema","typescript"],"install":[{"cmd":"npm install ts-migrate-mongoose","lang":"bash","label":"npm"},{"cmd":"yarn add ts-migrate-mongoose","lang":"bash","label":"yarn"},{"cmd":"pnpm add ts-migrate-mongoose","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core ORM dependency for which migrations are managed. This is a required peer dependency.","package":"mongoose","optional":false},{"reason":"Peer dependency specifically for integrations with the NestJS framework, as shown in examples and test setups.","package":"@nestjs/common","optional":true}],"imports":[{"note":"This is the primary class for programmatic migration management. Use named import for ESM. For CommonJS, access the named export from the `require` object.","wrong":"const Migrate = require('ts-migrate-mongoose').Migrate;","symbol":"Migrate","correct":"import { Migrate } from 'ts-migrate-mongoose';"},{"note":"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.","wrong":"import { IMigration } from 'ts-migrate-mongoose';","symbol":"IMigration","correct":"import type { IMigration } from 'ts-migrate-mongoose';"},{"note":"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.","wrong":"import runCLI from 'ts-migrate-mongoose';","symbol":"runCLI","correct":"import { runCLI } from 'ts-migrate-mongoose';"}],"quickstart":{"code":"import mongoose from 'mongoose';\nimport { Migrate, IMigration } from 'ts-migrate-mongoose';\n\n// 1. Define your migration class implementing IMigration\nclass AddTimestampToUsers implements IMigration {\n  async up(): Promise<void> {\n    console.log('Running up migration: AddTimestampToUsers');\n    // Example: Add a 'createdAt' and 'updatedAt' field to existing user documents\n    await mongoose.connection.db.collection('users').updateMany(\n      {}, // Filter for all documents\n      { $set: { createdAt: new Date(), updatedAt: new Date() } }, // Add new fields\n      { upsert: false } // Do not create new documents if no match\n    );\n    console.log('Migration AddTimestampToUsers (up) completed.');\n  }\n\n  async down(): Promise<void> {\n    console.log('Running down migration: AddTimestampToUsers');\n    // Example: Remove the 'createdAt' and 'updatedAt' fields from user documents\n    await mongoose.connection.db.collection('users').updateMany(\n      {}, // Filter for all documents\n      { $unset: { createdAt: '', updatedAt: '' } } // Remove fields\n    );\n    console.log('Migration AddTimestampToUsers (down) completed.');\n  }\n}\n\nasync function main() {\n  // 2. Connect to MongoDB using Mongoose\n  const mongoUri = process.env.MONGO_URI ?? 'mongodb://localhost:27017/my_ts_migrate_db';\n  await mongoose.connect(mongoUri);\n  console.log('Connected to MongoDB.');\n\n  // 3. Initialize the Migrate runner with configuration\n  const migrator = new Migrate({\n    migrationsPath: './migrations', // Directory where migration files are located (e.g., compiled JS files)\n    uri: mongoUri,\n    collectionName: 'migrations_log', // Collection to track applied migrations\n    // Other options like `templatePath`, `compilerOptions`, etc.\n  });\n\n  // In a real application, you would create a migration file (e.g., `migrations/20231027120000-add-timestamp-to-users.ts`)\n  // and `migrator.up()` or `migrator.down()` would discover and run it.\n  // For this quickstart, we'll demonstrate the core logic by manually running the `up` method.\n  \n  console.log('\\n--- Simulating a migration UP run ---');\n  const tempMigrationInstance = new AddTimestampToUsers();\n  await tempMigrationInstance.up();\n  console.log('Simulated UP migration complete. (In a real scenario, this would be tracked by the migrator.)\\n');\n\n  // To run all pending migrations (requires migration files in `migrationsPath`)\n  // await migrator.up();\n  // console.log('All pending migrations (up) completed.');\n\n  // To run all migrations down\n  // await migrator.down();\n  // console.log('All migrations (down) completed.');\n\n  // 4. Disconnect from MongoDB\n  await mongoose.disconnect();\n  console.log('Disconnected from MongoDB.');\n}\n\nmain().catch(console.error);","lang":"typescript","description":"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."},"warnings":[{"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.","message":"Version 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.","severity":"breaking","affected_versions":">=5.0.0"},{"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.","message":"Node.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.","severity":"breaking","affected_versions":">=5.2.0"},{"fix":"Ensure `mongoose` is installed in your project's dependencies: `npm install mongoose` or `pnpm add mongoose` or `yarn add mongoose`.","message":"It 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.","severity":"gotcha","affected_versions":">=4.0.0"},{"fix":"Upgrade to the latest `ts-migrate-mongoose` version (`npm install ts-migrate-mongoose@latest`) to incorporate the latest security patches and improvements.","message":"Version 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.","severity":"gotcha","affected_versions":">=5.3.0"},{"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.","message":"When 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.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"search_vec":"'5.3.2':32 'abil':59 'across':117 'activ':35 'also':98 'async/await':86 'backend':122 'cadenc':39 'chang':22 'cli':93 'commonj':114 'compat':53,109 'comprehens':83 'configur':68 'current':28 'custom':102 'databas':20 'design':17 'differenti':56 'direct':64,76 'enhanc':51 'env':74 'esm':112 'execut':89,106 'featur':49 'file':75 'fix':54 'flexibl':67 'framework':4,13,120 'frequent':40 'includ':57 'interfac':96 'introduc':47 'javascript':121 'key':55 'manag':19 'migrat':3,7,12,62,82,105,123,124,125 'migrate.json':71 'migrate.ts':72 'minor':42 'model':80 'modul':115 'mongo':128 'mongodb':24,66,127 'mongoos':2,8,15,79,126 'new':48 'node.js':119 'option':69,90 'patch':44 'programmat':95 'prune':100 'publish':41 'releas':38 'respons':37 'robust':11 'schema':21,129 'secur':50 'singl':104 'specif':16 'stabl':29 'state':63 'store':61 'support':84,99 'sync':101 'system':116 'templat':103 'ts':6 'ts-migrate-mongoos':5 'typescript':1,26,130 'updat':45 'util':77 'various':118 'versatil':88 'version':30 'via':70 'within':65,81","created_at":"2026-04-20T01:58:08.776934+00:00","updated_at":"2026-04-20T01:58:08.776934+00:00","problems":[{"fix":"Run `npm install mongoose ts-migrate-mongoose` (or equivalent for pnpm/yarn) to ensure both packages are correctly installed.","cause":"One of the core runtime dependencies (mongoose or ts-migrate-mongoose itself) is not installed in your project's node_modules.","error":"Error: Cannot find module 'mongoose' or Error: Cannot find module 'ts-migrate-mongoose'"},{"fix":"Upgrade your Node.js environment to version 20 or newer. Use `nvm install 20 && nvm use 20` or similar methods.","cause":"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.","error":"Error: Node.js version X.Y.Z is not supported. This package requires Node.js >=20."},{"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`).","cause":"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.","error":"Error: Unknown argument: --uri or Error: Unknown argument: --database"},{"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(...)`.","cause":"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.","error":"TypeError: (0 , ts_migrate_mongoose_1.Migrate) is not a constructor"}],"ecosystem":"npm","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"ts-migrate-mongoose","cli_version":null,"type":"library","homepage":"https://kristianmandrup.github.io/ts-migrate-mongoose","github":"https://github.com/ilovepixelart/ts-migrate-mongoose","docs":null,"changelog":null,"pypi":null,"npm":"https://www.npmjs.com/package/ts-migrate-mongoose","openapi_spec":null,"status_page":null,"smithery":null,"categories":["database","devops"],"base_url":null,"auth_type":null,"provenance":{"verified_status":null,"verified_at":null,"last_verified":"2026-06-17","next_check":"2026-07-18","install_tag":null}}