# Add Database Migrations to a Mongoose App

Yes. An agent adds migrate-mongo to your Mongoose app, moves index creation into a first migration, tests it against the test database and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-database-migrations/mongoose/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the schema reaches the database today, because in a Mongoose app there is no migration step: indexes are built when models compile and documents change shape whenever the code does. In a project like hagopj13/node-express-boilerplate, `package.json` depends on `mongoose` `^5.7.7`, resolved to 5.13.20 in `yarn.lock` with the `mongodb` driver at 3.7.4 beneath it, `express` `^4.17.1`, `joi` `^17.3.0` and `winston`, tests run with `jest -i` and `supertest`, lint is `eslint .` under `airbnb-base` with the `security` and `prettier` plugins and `no-console` set to `error`, and `.husky/pre-commit` runs `lint-staged` on every `.js` file. `src/config/config.js` validates the environment with Joi, requires `MONGODB_URL`, appends `-test` to it when `NODE_ENV` is `test`, and passes `useCreateIndex: true` in the connection options. `src/index.js` connects, then listens. `src/models/user.model.js` declares `email` as `unique: true` and `src/models/token.model.js` declares `token` with `index: true`, so both indexes are created by Mongoose at boot. `.travis.yml` runs on Node 12 with a `mongodb` service, `docker-compose.yml` uses `mongo:4.2.1-bionic`, and `engines.node` is `>=12.0.0`.

The tool is `migrate-mongo`, whose current release, 14.0.7, requires Node 20 and lists the `mongodb` driver `^4.4.1 || ^5.0.0 || ^6.0.0 || ^7.0.0` as a peer. That peer is the first thing the agent has to reconcile: the app's driver is the 3.7.4 that Mongoose 5 pins, and Yarn 1 installs no peers, so the agent adds `mongodb` at a 6.x release as a direct dependency for the migration tool to use while Mongoose keeps its own nested copy. Both talk to the same server; only the client library differs. The agent raises `engines.node` to `>=20`, moves `.travis.yml` from Node 12 to 20, and leaves the `node:alpine` base in `Dockerfile` as it is, since that tag already tracks a current release. It says in the pull request that upgrading Mongoose itself is a separate change.

The configuration reuses the app's own. `migrate-mongo-config.js` requires `src/config/config.js` and takes `mongoose.url` from it, so the `-test` suffix and the Joi validation apply to migrations exactly as they do to the server, with `migrationsDir: 'migrations'`, `changelogCollectionName: 'changelog'` and `lockCollectionName: 'changelog_lock'`. The first file in `migrations/`, created with `migrate-mongo create schema-indexes`, builds the two indexes the models declare, `users.email` unique and `tokens.token`, in `up`, and drops them in `down`; `src/config/config.js` then passes `autoIndex: false` in production so Mongoose stops building indexes at startup and the migration owns them, while development and test keep `autoIndex` so a fresh database works without a migrate step. `package.json` gains `migrate`, `migrate:down`, `migrate:status` and `migrate:create` scripts, and the README's Commands section gets the four lines. Every new file passes `eslint` under the repository's rules, which matters because `lint-staged` runs on commit.

Tests run in Jest against the `-test` database the way the integration suite already does. `tests/integration/migrations.test.js` uses migrate-mongo's programmatic API, `database.connect()`, `up` and `status`, to apply the migration to a clean database, asserts `status` lists the file as `APPLIED`, asserts `db.collection('users').indexes()` contains an `email_1` entry with `unique: true` and `tokens` a `token_1` entry, then runs `down` and asserts both are gone and the changelog is empty. The agent runs `yarn test`, `yarn lint` and `yarn prettier` in its sandbox against a MongoDB it starts, then `yarn migrate:status`, `yarn migrate` and `yarn migrate:status` again against the development database, and pastes the three status tables.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add database migrations to this Mongoose app with migrate-mongo. Read package.json, yarn.lock (the resolved mongoose and mongodb versions), .travis.yml, Dockerfile, docker-compose.yml, .eslintrc.json, src/config/config.js, src/index.js, every model in src/models, tests/utils/setupTestDB.js and the README's Commands section first. Install migrate-mongo, satisfy its mongodb peer dependency with a direct dependency without changing the Mongoose version, and raise the Node floor and the CI Node version to what it needs. Write migrate-mongo-config.js that reads the URL from src/config/config.js, a first migration that creates the indexes the models declare with a matching down, set autoIndex false in production only, add migrate, migrate:down, migrate:status and migrate:create scripts, and document them in the README. Add a Jest integration test that applies the migration to the test database, checks the indexes and the changelog, and rolls it back. Run yarn test, yarn lint, yarn prettier and the migrate scripts, and open a pull request with the output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request adds `migrate-mongo-config.js`, `migrations/<timestamp>-schema-indexes.js` and `tests/integration/migrations.test.js`, and changes `package.json`, `yarn.lock`, `.travis.yml`, `src/config/config.js` and `README.md`. Its description explains the two-driver arrangement in one paragraph, pastes the `migrate-mongo status` table before and after `up`, and includes the `jest`, `eslint` and `prettier` output.

A reviewer sees that the migration config reads the same validated URL the app uses, that the first migration does only what the models already declare so nothing changes for a database that has the indexes, and that the new test runs in the same `-test` database and cleans up after itself. The run's record keeps every command, including the MongoDB the agent started for the suite.

Before merging, a reviewer decides where `yarn migrate` runs in their deploy, whether `autoIndex` should also be off in staging, and whether the next migration should be a data change such as backfilling a field. The models, services and routes are unchanged.

## Run it on every Mongoose service whose schema changes ship without a migration

A team with several Express services on this boilerplate starts one run per repository from its own server: a `POST /o/{org}/sessions` each, with the repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started instead of opening a second pull request. Each run reads its own models, so a service with more indexes gets each one in the first migration, and one already on Mongoose 7 or later gets the peer dependency satisfied by the driver it already has.

After that, a Linear issue labelled `migration` in the Project can start a run through an automation with a `linear` trigger and the prompt "write the migrate-mongo migration this issue describes with a working down, update the affected model, add a test that applies and rolls it back, run yarn test and open a pull request". The trigger adds the issue after the prompt, and the run reads it through the Linear connection, so each data change arrives as a reviewed file in `migrations/` rather than a script someone runs once.

## Why run it on Rush?

Adding a migration tool to a Mongoose app is mostly about the parts that do not fit: a peer dependency the ORM's pinned driver cannot satisfy, a Node floor the CI config does not meet, and index creation that already happens somewhere else. The agent reads the lockfile and the config before installing anything, resolves each mismatch explicitly, and runs the migration up and down against a real server in its sandbox before the pull request exists.

Every command stays with the run, from the `status` tables to the Jest output, and the pull request quotes them. Several services on the same boilerplate can get the change at once, each in its own sandbox, with its own evidence and its own pull request.

## Frequently asked questions

### Why are there two mongodb drivers in node_modules?

Mongoose 5 pins the 3.7.4 driver and `migrate-mongo` 14 needs 4.4 or later as a peer. Yarn 1 does not install peers, so the agent adds a 6.x driver as a direct dependency for the migration tool; Mongoose keeps its nested copy. Both connect to the same database. Upgrading Mongoose later removes the duplication, and the pull request says so.

### Why turn off autoIndex only in production?

In development and test a fresh database should work without running a migrate step, and the existing suite relies on that. In production, index builds at boot can block a large collection, so the migration becomes the one place indexes are created, and `autoIndex: false` makes sure the app no longer races it.

### Does the first migration change an existing database?

No. It creates the same two indexes the models already declare, with the same names Mongoose gives them, so on a database where they exist it is a no-op apart from the `changelog` entry. The `down` drops them, which the test exercises on the `-test` database only.

### How do I write a data migration later?

Run `yarn migrate:create <description>` to get a file with `up(db, client)` and `down(db, client)`, use the driver's `db.collection(...).updateMany` or similar in each, and run `yarn migrate`. The README section the pull request adds shows the pattern, and the automation above drafts one from a Linear issue.

### Does this pass the repository's lint rules?

Yes. The migration, the config and the test are written to the `airbnb-base` ruleset with the `security` and `prettier` plugins, with no `console` calls since `no-console` is an error, and `lint-staged` runs `eslint` on them at commit time as it does for every file.

## More Mongoose jobs

- [Add Dependabot to an Express and Mongoose API](https://getrush.ai/run/add-dependabot/mongoose/)
- [Add Full-Text Search to a Mongoose API](https://getrush.ai/run/add-full-text-search/mongoose/)
- [Add Google Login to an Express and Mongoose API](https://getrush.ai/run/add-google-login/mongoose/)

## The same job on other stacks

- [Move a Sequelize App From sync() to Migrations](https://getrush.ai/run/add-database-migrations/sequelize/)
- [Add Database Migrations to a Slim 4 App](https://getrush.ai/run/add-database-migrations/slim/)
- [Replace TypeORM synchronize with Migrations](https://getrush.ai/run/add-database-migrations/typeorm/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
