# Upgrade Mongoose 5 to the Current Major in an Express API

Yes. An agent upgrades Mongoose 5 to the current major, removes the dropped connection options, fixes ObjectId and remove() calls, and runs Jest on a real MongoDB.

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

## What the agent does

The agent reads every place Mongoose is used before it changes the version. In an API like hagopj13/node-express-boilerplate, `package.json` pins `mongoose ^5.7.7` and `yarn.lock` resolves it to 5.13.20 on the `mongodb` 3.7.4 driver, next to `express ^4.17.1`, `jest ^26.0.1`, `supertest`, `faker ^5.1.0` and an `engines` field of `node >=12.0.0`. `src/config/config.js` builds the connection options as `useCreateIndex`, `useNewUrlParser` and `useUnifiedTopology`, which `src/index.js` passes to `mongoose.connect` and `tests/utils/setupTestDB.js` passes again in `beforeAll`. `src/models/user.model.js` and `token.model.js` define schemas with custom `validate` functions, `timestamps` and two plugins from `src/models/plugins/`, `toJSON` and `paginate`, where `paginate` chains `countDocuments().exec()` and `find().sort().skip().limit()`. `src/services/user.service.js` deletes with `user.remove()`, and `src/services/auth.service.js` calls `refreshTokenDoc.remove()` twice. `tests/fixtures/user.fixture.js` builds ids with `mongoose.Types.ObjectId()` and no `new`. `src/middlewares/error.js` maps any `mongoose.Error` to a 400.

Those are exactly the lines later majors break. Mongoose 6 removed `useNewUrlParser`, `useUnifiedTopology` and `useCreateIndex` as options and rejects a connection that passes them, and its `ObjectId` is a class, so `mongoose.Types.ObjectId()` without `new` throws. Mongoose 7 removed `Document.prototype.remove()` in favour of `deleteOne()`. The agent bumps `mongoose` to the current major in `package.json` and `yarn.lock`, deletes the three options from `config.js` so the `options` object becomes empty and is dropped from both `connect` calls, rewrites the three fixture ids as `new mongoose.Types.ObjectId()`, and replaces the three `remove()` calls with `deleteOne()`. It reads the release notes between 5 and the target for anything else the code touches, checks that the `validate(value)` throw pattern, `enum`, `unique`, `private` as a custom schema option and `schema.statics` still behave, and confirms the driver the new Mongoose brings supports the `mongo:4.2.1-bionic` image `docker-compose.yml` runs, or says in the pull request if it does not.

The `engines` field needs a decision too: Node 12 cannot run a current Mongoose, so the agent raises `engines.node` to the floor the new version declares and updates the `.travis.yml` matrix that still names node 12, or notes that the file is stale if CI has moved. `Dockerfile` builds from `node:alpine` without a tag, so it picks up whatever current Node is and needs no change, which the pull request states. `express-mongo-sanitize`, `passport-jwt` and the `toJSON` plugin do not depend on the Mongoose major.

The suite is the proof, and it needs a MongoDB: `setupTestDB` connects to `MONGODB_URL` with `-test` appended. The sandbox has no Docker, so the agent adds `mongodb-memory-server` as a dev dependency, starts one instance in `tests/utils/setupTestDB.js` when `MONGODB_URL` is not set, and otherwise keeps the existing behaviour so `yarn docker:test` still works. It then runs `yarn install`, `yarn lint` and `yarn test`, which runs Jest with `-i --detectOpenHandles`, through the integration tests under `tests/integration/` that create users and tokens, log in, refresh and log out, and the unit tests for the plugins and the error middleware. Failures that the upgrade causes are fixed in the application code; a test that encoded old behaviour is changed with the reason in the commit message.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Upgrade Mongoose in this Express API from the 5.x the lockfile pins to the current major. Read package.json, yarn.lock, .travis.yml, Dockerfile, docker-compose.yml, src/config/config.js, src/index.js, every file under src/models/ and src/services/, src/middlewares/error.js, tests/utils/setupTestDB.js, tests/fixtures/user.fixture.js and jest.config.js first. Bump mongoose, remove the useCreateIndex, useNewUrlParser and useUnifiedTopology options from config.js and both connect calls, write new in front of every mongoose.Types.ObjectId() in the fixtures, replace each document remove() call with deleteOne(), and read the release notes between the old and new majors for anything else the code uses. Raise engines.node to the floor the new Mongoose requires and update .travis.yml to match. Add mongodb-memory-server as a dev dependency and start it in setupTestDB.js when MONGODB_URL is not set, keeping the existing connection when it is. Run yarn install, yarn lint and yarn test, fix what breaks in application code, explain any test you change, and open a pull request listing every behaviour change by file and line and whether the MongoDB image in docker-compose.yml is still supported by the new driver.",
  "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

What comes back is a pull request that changes `package.json`, `yarn.lock`, `src/config/config.js`, `src/index.js`, `src/services/user.service.js`, `src/services/auth.service.js`, `tests/fixtures/user.fixture.js`, `tests/utils/setupTestDB.js` and `.travis.yml`. The models, the plugins, the controllers and the routes are untouched.

The description lists each breaking change with the file and line it affected, states the Node floor and the MongoDB server range the new driver supports, and quotes the `yarn lint` and `yarn test` output from the sandbox. The transcript at `GET /o/{org}/sessions/{id}/messages` keeps every command.

Before merging, a reviewer decides whether to keep `mongodb-memory-server` or point CI at a service container, whether to bump the `mongo` image in `docker-compose.yml` at the same time, and whether `strictQuery`, whose default changed across these majors, should be set explicitly in `config.js` so query filters behave the same before and after.

## Run it on every Monday morning

Create an automation in the Project with a `schedule` trigger, `cron` set to `0 9 * * 1` in your `timezone`, and a prompt that asks for the next major of any dependency more than one major behind, with the test suite run and the breaking changes listed. Each run opens one pull request on its own branch, and a run whose tests cannot be made to pass stops at `needs_review` with the reason, so an ORM that needs a hand does not block the week's other bumps.

For this one upgrade now, send this body to `POST /o/{org}/sessions` with a `request_id` that is a UUID v5 of the repository's full name and the week, so a retry returns the run it already started. The key's `webhook_url` reports `run.completed` with `session_url` when the turn finishes.

## Why run it on Rush?

A three-major ORM upgrade is a list of small breaks spread across config, services and test fixtures, and the only honest check is the integration suite against a real MongoDB, which on a laptop means a local `mongod` or a container and a test database holding whatever the last interrupted run left. The agent reads every Mongoose call site first, applies the known removals, then runs the suite on a clean machine of its own with a MongoDB it started there, as many times as it takes.

The pull request carries the list of changes with file and line and the test output, so a reviewer checks the reasoning instead of rediscovering it, and a fleet of services on the same boilerplate can be upgraded at once, each in its own sandbox.

## Frequently asked questions

### Why do the connection options have to go?

Mongoose 6 stopped accepting `useNewUrlParser`, `useUnifiedTopology` and `useCreateIndex` and behaves as if all three were on. Passing them makes the connection fail, which is why both `mongoose.connect` calls lose the options object.

### What about remove() on documents?

It was removed in Mongoose 7. `deleteOne()` on the document is the replacement in `user.service.js` and `auth.service.js`, and `Token.deleteMany` elsewhere in `auth.service.js` was already the model-level form.

### Why mongodb-memory-server rather than installing MongoDB?

The test setup already appends `-test` to `MONGODB_URL` and wipes collections between tests; a memory server gives each `yarn test` a fresh instance with no service to manage, in the sandbox and on a laptop alike. The change is guarded so `docker:test`, which sets `MONGODB_URL`, still uses the compose service.

### Will the paginate and toJSON plugins keep working?

They use `schema.statics`, `countDocuments`, `find` with `sort`, `skip`, `limit` and `populate`, and the `toJSON` transform option, all of which the current API keeps. The unit tests under `tests/unit/models/plugins/` run against the new version to confirm it.

### Does the mongo:4.2.1 image still work?

The pull request states the server range the new driver supports after reading its release notes, and recommends a newer image if 4.2 is outside it. The upgrade of the image itself is left as a separate change so each can be reverted alone.

## More Mongoose jobs

- [Add Account Lockout to a Mongoose and Express App](https://getrush.ai/run/add-account-lockout/mongoose/)
- [Add an Audit Log to a Mongoose and Express API](https://getrush.ai/run/add-audit-log/mongoose/)
- [Add Cursor Pagination to a Mongoose and Express API](https://getrush.ai/run/add-cursor-pagination/mongoose/)

## More jobs like this: Upgrade dependencies weekly

- [Upgrade an Express App to Node 24](https://getrush.ai/run/upgrade-node-version/express/)
- [Upgrade a NestJS App to Node 24](https://getrush.ai/run/upgrade-node-version/nestjs/)
- [Upgrade a Node.js App to Node 24](https://getrush.ai/run/upgrade-node-version/nodejs/)

## 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/)
