{"id":15066186,"url":"https://github.com/ilovepixelart/ts-migrate-mongoose","last_synced_at":"2026-04-13T00:01:58.579Z","repository":{"id":58924449,"uuid":"534558188","full_name":"ilovepixelart/ts-migrate-mongoose","owner":"ilovepixelart","description":"A migration framework for Mongoose, built with TypeScript.","archived":false,"fork":false,"pushed_at":"2025-04-05T09:51:43.000Z","size":2404,"stargazers_count":80,"open_issues_count":0,"forks_count":8,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-06T15:48:50.572Z","etag":null,"topics":["cli","cli-app","cli-tool","migrations","mongodb","mongoose","node","nodejs","npm","npm-package","programmatic","ts","ts-migrate-mongoose","tsx","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ilovepixelart.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-09-09T08:18:00.000Z","updated_at":"2025-04-05T09:51:46.000Z","dependencies_parsed_at":"2023-11-27T22:26:26.536Z","dependency_job_id":"acd65c81-2da0-4701-8cbe-f41635c82bdc","html_url":"https://github.com/ilovepixelart/ts-migrate-mongoose","commit_stats":{"total_commits":558,"total_committers":5,"mean_commits":111.6,"dds":"0.17025089605734767","last_synced_commit":"ce0e4785e4f12d77f6e70c0645a6c6b03f3279fd"},"previous_names":[],"tags_count":112,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilovepixelart%2Fts-migrate-mongoose","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilovepixelart%2Fts-migrate-mongoose/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilovepixelart%2Fts-migrate-mongoose/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilovepixelart%2Fts-migrate-mongoose/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ilovepixelart","download_url":"https://codeload.github.com/ilovepixelart/ts-migrate-mongoose/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248654089,"owners_count":21140236,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cli","cli-app","cli-tool","migrations","mongodb","mongoose","node","nodejs","npm","npm-package","programmatic","ts","ts-migrate-mongoose","tsx","typescript"],"created_at":"2024-09-25T01:03:05.758Z","updated_at":"2026-04-13T00:01:58.551Z","avatar_url":"https://github.com/ilovepixelart.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ts-migrate-mongoose\n\nA migration framework for Mongoose, built with TypeScript.\n\n[![npm](https://img.shields.io/npm/v/ts-migrate-mongoose)](https://www.npmjs.com/package/ts-migrate-mongoose)\n[![npm](https://img.shields.io/npm/dt/ts-migrate-mongoose)](https://www.npmjs.com/package/ts-migrate-mongoose)\n[![GitHub](https://img.shields.io/github/license/ilovepixelart/ts-migrate-mongoose)](https://github.com/ilovepixelart/ts-migrate-mongoose/blob/main/LICENSE)\n\\\n[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=ilovepixelart_ts-migrate-mongoose\u0026metric=coverage)](https://sonarcloud.io/summary/new_code?id=ilovepixelart_ts-migrate-mongoose)\n[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=ilovepixelart_ts-migrate-mongoose\u0026metric=alert_status)](https://sonarcloud.io/summary/new_code?id=ilovepixelart_ts-migrate-mongoose)\n\\\n[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=ilovepixelart_ts-migrate-mongoose\u0026metric=reliability_rating)](https://sonarcloud.io/summary/new_code?id=ilovepixelart_ts-migrate-mongoose)\n[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=ilovepixelart_ts-migrate-mongoose\u0026metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=ilovepixelart_ts-migrate-mongoose)\n[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=ilovepixelart_ts-migrate-mongoose\u0026metric=security_rating)](https://sonarcloud.io/summary/new_code?id=ilovepixelart_ts-migrate-mongoose)\n\\\n[![Socket Badge](https://badge.socket.dev/npm/package/ts-migrate-mongoose)](https://socket.dev/npm/package/ts-migrate-mongoose)\n[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/ilovepixelart/ts-migrate-mongoose/badge)](https://securityscorecards.dev/viewer/?uri=github.com/ilovepixelart/ts-migrate-mongoose)\n[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/12477/badge)](https://www.bestpractices.dev/en/projects/12477)\n\n## Motivation\n\nts-migrate-mongoose is a migration framework for mongoose\n\\\nI need a way to manage database migrations for mongoose models, run them from the CLI or programmatically, and keep track of which migrations have been applied. It should support both ESM and CommonJS, work with all major Node.js frameworks, and be flexible enough to handle complex migration scenarios.\n\n## Supports and tested with\n\n```json\n{\n  \"node\": \"20.x || 22.x || 24.x\",\n  \"mongoose\": \"\u003e=6.6.0 \u003c10\"\n}\n```\n\nCI tests against mongoose `6.12.2`, `7.6.4`, `8.23.0`, and `9.4.1`.\n\n## Features\n\n- Stores migration state in MongoDB\n- Flexible configuration using `migrate.json`, `migrate.ts`, `.env`\n- Utilizes mongoose models during migrations\n- Supports async/await in migrations\n- Run migrations from the CLI or programmatically\n- Prune old migrations and sync new migrations\n- Create custom templates for migrations\n- Run individual migration up/down using -s, --single\n- Supports ESM and CommonJS\n\n## Installation\n\n`mongoose` is a peer dependency — install it alongside `ts-migrate-mongoose`.\n\n```bash\nnpm install ts-migrate-mongoose mongoose\npnpm add ts-migrate-mongoose mongoose\nyarn add ts-migrate-mongoose mongoose\nbun add ts-migrate-mongoose mongoose\n```\n\nOr globally:\n\n```bash\nnpm install -g ts-migrate-mongoose mongoose\npnpm add -g ts-migrate-mongoose mongoose\nyarn global add ts-migrate-mongoose mongoose\nbun add -g ts-migrate-mongoose mongoose\n```\n\n## Example\n\nWorks with any Node.js framework — Express, Fastify, Koa, Hono, Nest, etc.\n\\\nHow to use it with:\n\n- Express: [ts-express-tsx](https://github.com/ilovepixelart/ts-express-tsx), [ts-express-esbuild](https://github.com/ilovepixelart/ts-express-esbuild)\n- Nest: [ts-express-nest](https://github.com/ilovepixelart/ts-express-nest)\n\n## Migrations and alias imports\n\nIf you are using alias imports in your project, you can use `tsconfig.json` paths to resolve them for your project.\n\n## Configuration\n\nIf you don't want to provide `-d` or `--uri` flag in CLI or Programmatic mode, you can configure it.\n\\\nCreate a `migrate.json` or `migrate.ts` or `.env` file in the root of your project:\n\n- `migrate.json`\n\n```json\n{\n  \"uri\": \"mongodb://localhost/my-db\",\n  \"collection\": \"migrations\",\n  \"migrationsPath\": \"./migrations\",\n  \"templatePath\": \"./migrations/template.ts\",\n  \"autosync\": false\n}\n```\n\n- `migrate.ts`\n\n```typescript\nexport default {\n  uri: \"mongodb://localhost/my-db\",\n  collection: \"migrations\",\n  migrationsPath: \"./migrations\",\n  templatePath: \"./migrations/template.ts\",\n  autosync: false,\n  connectOptions: {\n    autoIndex: true,\n  },\n};\n```\n\n- `.env`\n\n```bash\n# You can set this variable or in your CI/CD pipeline\n# Or use --mode flag in CLI mode to switch between .env files\nMIGRATE_MODE=development\n```\n\nIf mode is set, it will look for `.env.[mode]` file in the root of your project\n\\\nFor example, if `MIGRATE_MODE=development` it will look for `.env.development` file\n\\\nIf mode is not set, it will look for `.env` file in the root of your project\n\n```bash\n.env                # loaded in all cases\n.env.local          # loaded in all cases (used as override for local development)\n.env.[mode]         # only loaded in specified mode\n.env.[mode].local   # only loaded in specified mode (used as override for local development)\n```\n\n```bash\n# Example .env file content\nMIGRATE_MONGO_URI=mongodb://localhost/my-db\nMIGRATE_MONGO_COLLECTION=migrations\nMIGRATE_CONFIG_PATH=./migrate\nMIGRATE_MIGRATIONS_PATH=./migrations\nMIGRATE_TEMPLATE_PATH=./migrations/template.ts\nMIGRATE_AUTOSYNC=false\n```\n\n| Config file          | `.env` / export          | Default      | Required | Description                                      |\n| -------------------- | ------------------------ | ------------ | -------- | ------------------------------------------------ |\n| mode                 | MIGRATE_MODE             | -            | No       | environment mode to use .env.[mode] file         |\n| uri                  | MIGRATE_MONGO_URI        | -            | Yes      | mongo connection string                          |\n| collection           | MIGRATE_MONGO_COLLECTION | migrations   | No       | collection name to use for the migrations        |\n| configPath           | MIGRATE_CONFIG_PATH      | -            | No       | will lookup ./migrate[.ts,.js,.json] in root     |\n| migrationsPath       | MIGRATE_MIGRATIONS_PATH  | ./migrations | No       | path to the migration files                      |\n| templatePath         | MIGRATE_TEMPLATE_PATH    | -            | No       | template file to use when creating a migration   |\n| autosync             | MIGRATE_AUTOSYNC         | false        | No       | automatically sync new migrations without prompt |\n| connectOptions       | -                        | -            | No       | mongoose connection options (config file only)   |\n\n## Getting started with the CLI\n\nExplore and learn commands, rest of the tutorial will be using npm\n\n```bash\nnpx migrate -h\npnpm migrate -h\nyarn migrate -h\nbun migrate -h\n```\n\n```text\nCLI migration tool for mongoose\n\nUsage: migrate \u003ccommand\u003e [options]\n\nCommands:\n  list                       list all migrations\n  create \u003cmigration-name\u003e    create a new migration file\n  up [migration-name]        run all migrations or a specific migration if name provided\n  down \u003cmigration-name\u003e      roll back migrations down to given name\n  prune                      delete extraneous migrations from migration folder or database\n\nOptions:\n  -f, --config-path \u003cpath\u003e        path to the config file\n  -d, --uri \u003cstring\u003e              mongo connection string\n  -c, --collection \u003cstring\u003e       collection name to use for the migrations\n  -a, --autosync \u003cboolean\u003e        automatically sync new migrations without prompt\n  -m, --migrations-path \u003cpath\u003e    path to the migration files\n  -t, --template-path \u003cpath\u003e      template file to use when creating a migration\n      --mode \u003cstring\u003e             environment mode to use .env.[mode] file\n  -s, --single                    run single migration (up/down only)\n  -h, --help                      display help\n  -v, --version                   display version\n```\n\nBefore you start make sure you setup .env file or migrate.ts/json file so you don't need to provide -d on each command\n\n```bash\nnpx migrate create add-users -d mongodb://localhost/my-db\n```\n\nIn case you want to run just one migration up or down use option --single\n\n```bash\nnpx migrate create first-migration\nnpx migrate create second-migration\nnpx migrate list\nnpx migrate up second-migration -s # will migrate up only second-migration\nnpx migrate down second-migration -s # will migrate down only second-migration\nnpx migrate up -s # will migrate up first-migration\n```\n\n## Options override order\n\nNote that options are overridden in the following order:\n\n- Command line args \u003e Env vars \u003e Config file\n\n## Migration files\n\nThis example demonstrates how you can create a migration file using the CLI\n\\\nBy default, ts-migrate-mongoose assumes your migration folder exists (if it does not it will create one for you)\n\nHere's an example of a migration created using:\n\n```bash\nnpx migrate create first-migration\npnpm migrate create first-migration\nyarn migrate create first-migration\nbun migrate create first-migration\n```\n\nExecuting the above command will create a migration file in the `./migrations` folder with the following content:\n\n- 1673525773572-first-migration.ts\n\n```typescript\n// Import your schemas here\nimport type { Connection } from 'mongoose'\n\nexport async function up (connection: Connection): Promise\u003cvoid\u003e {\n  // Write migration here\n}\n\nexport async function down (connection: Connection): Promise\u003cvoid\u003e {\n  // Write migration here\n}\n```\n\n## Using mongoose models in your migrations\n\nAs long as you can import the references to your models you can use them in migrations\n\\\nBelow is an example of a typical setup in a mongoose project:\n\n- models/User.ts - defines the User model\n\n```typescript\nimport { Schema, model, models } from 'mongoose'\n\ninterface IUser {\n  firstName: string\n  lastName?: string\n}\n\nexport const UserSchema = new Schema\u003cIUser\u003e({\n  firstName: {\n    type: String,\n    required: true\n  },\n  lastName: {\n    type: String\n  }\n})\n\nexport default models.User ?? model\u003cIUser\u003e('User', UserSchema)\n```\n\n- 1673525773572-first-migration-demo.ts - your migration file\n\n```typescript\nimport { UserSchema } from '../models/User'\nimport type { Connection } from 'mongoose'\n\nexport async function up(connection: Connection) {\n  const User = connection.model('User', UserSchema)\n  await User.create([\n    {\n      firstName: 'John',\n      lastName: 'Doe',\n    },\n    {\n      firstName: 'Jane',\n      lastName: 'Doe',\n    },\n  ])\n}\n\nexport async function down(connection: Connection) {\n  const User = connection.model('User', UserSchema)\n  await User.deleteMany({ firstName: { $in: ['Jane', 'John'] } }).exec()\n}\n```\n\n## Programmatic mode\n\nWorks with any Node.js framework — Express, Fastify, Koa, Hono, etc:\n\n```typescript\nimport { Migrator } from 'ts-migrate-mongoose'\n\nconst migrator = await Migrator.connect({\n  uri: 'mongodb://localhost:27017/my-db',\n  autosync: true,\n})\n\nawait migrator.run('up')        // Run all pending migrations\nawait migrator.run('down', 'x') // Roll back a specific migration\nawait migrator.list()           // List all migrations and their status\nawait migrator.create('name')   // Create a new migration file\nawait migrator.prune()          // Remove orphaned migrations from DB\nawait migrator.close()          // Close the connection\n```\n\n### Express / Fastify / Koa / Hono\n\n```typescript\nimport { Migrator } from 'ts-migrate-mongoose'\n\n// Run before starting your server\nconst migrator = await Migrator.connect({\n  uri: process.env.MONGO_URI ?? 'mongodb://localhost:27017/my-db',\n  autosync: true,\n})\nawait migrator.run('up')\nawait migrator.close()\n\n// Start your server\napp.listen(3000)\n```\n\n### NestJS (because it's special)\n\nImport `MigrationModule` from `ts-migrate-mongoose/nest`:\n\n```typescript\nimport { MigrationModule } from 'ts-migrate-mongoose/nest'\n\n@Module({\n  imports: [\n    MongooseModule.forRoot(process.env.MONGO_URI),\n    MigrationModule.forRootAsync({\n      inject: [ConfigService],\n      useFactory: (config: ConfigService) =\u003e ({\n        uri: config.get\u003cstring\u003e('MONGO_URI'),\n        autosync: true,\n      }),\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nRuns all pending up migrations on application bootstrap. For custom control:\n\n```typescript\nMigrationModule.forRoot({\n  uri: process.env.MONGO_URI,\n  onBootstrap: async (migrator) =\u003e {\n    await migrator.run('down', 'test')\n    await migrator.prune()\n    await migrator.run('up')\n  },\n})\n```\n\nSee [programmatic usage examples](/examples/programmatic-usage) for the full API and more examples.\n\n## Contributing\n\nCheck [CONTRIBUTING.md](CONTRIBUTING.md)\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details\n\n## Notes\n\n- Currently, the `-d` or `--uri` must include the database to use for migrations in the uri.\n- Example: `-d mongodb://localhost:27017/development`\n- If you don't want to pass it every time feel free to use `migrate.ts` or `migrate.json` config file or an environment variable\n- Feel Free to check out the `/examples` folder in the project to get a better idea of usage in Programmatic and CLI mode\n\n## Check my other projects\n\n- [ts-patch-mongoose](https://github.com/ilovepixelart/ts-patch-mongoose) - Patch history \u0026 events plugin for mongoose\n- [ts-cache-mongoose](https://github.com/ilovepixelart/ts-cache-mongoose) - Cache plugin for mongoose Queries and Aggregate (in-memory, redis)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Filovepixelart%2Fts-migrate-mongoose","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Filovepixelart%2Fts-migrate-mongoose","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Filovepixelart%2Fts-migrate-mongoose/lists"}