# Fix "Model.find() no longer accepts a callback" After a Mongoose Upgrade

Yes. An agent ports every Mongoose callback to promises, keeps the error handling each one had, runs the API tests against MongoDB, and opens a pull request.

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

## What the agent does

The agent counts the callbacks before it picks a target version, because the count decides how the port is done. In an Express API like ealeksandrov/NodeAPI, `package.json` asks for `mongoose` `^6.13.x`, the last major line that accepts callbacks. A search for `function (err` finds twenty Mongoose calls: five in `libs/auth/auth.js`, four in `libs/auth/oauth2.js`, five in `libs/routes/articles.js` and six in `generateData.js`. Three more in `oauth2.js` pass a named handler instead, `RefreshToken.deleteMany(data, errorHandler)`, its `AccessToken` twin and `refreshToken.save(errorHandler)`, and a text search for inline functions misses them. That makes twenty-three.

It then gets a baseline and reproduces the failure, both against a real database. The sandbox has no Docker, so the agent runs MongoDB with the `mongodb-memory-server` package on port 27017 and follows the steps in `.github/workflows/ci.yml`: start the server, `npm run generate`, `npm test`. On Mongoose 6.13.5 the tape suite reports 18 assertions passing. On 9.12.0 the seed script dies on its first line of work with `MongooseError: Model.deleteMany() no longer accepts a callback`. The server still starts and connects, then answers every authenticated request with a 500 whose message is `Model.findOne() no longer accepts a callback`, and the suite reports 1 pass and 12 failures.

The port is where judgement comes in. Passport strategies and oauth2orize exchanges are callback APIs themselves, so each query becomes an `await` inside a `try` that still ends in exactly one `done(...)`. The agent keeps every branch the callback had: `done(null, false)` for a missing client, the `Token expired` message, the 500 and 404 bodies in the article routes. Two places need more than a rewrite. In `generateTokens`, two deletes and two saves are started without waiting for one another, and three of them share a handler that can call `done` with an error while the fourth also calls it. In the bearer strategy, an expired token triggers a `deleteMany` whose error handler calls `done`, and the next line calls `done` again. With promises the order has to be written down, so the agent awaits the deletes, then the saves, and reports both spots as behaviour it made explicit.

Last, it settles the version. Mongoose 9.12.0 declares Node 20.19 or newer and the workflow installs Node 16, which Mongoose 8 still accepts. The agent either stops at 8 or raises the workflow's Node version, according to the prompt, and checks the pinned `mongo:3.4.4` image in `docker-compose.yml` against the server versions the new driver supports.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "This project fails after a Mongoose upgrade with: MongooseError: Model.find() no longer accepts a callback. Port it to promises. Read package.json, the lock file, the CI workflow and any Docker files; report the Mongoose range, the Node version CI uses, and the MongoDB version the project runs against. Find every Mongoose call that takes a callback: model and query methods (find, findOne, findById, save, deleteMany, updateOne, countDocuments, exec and the rest), including calls that pass a named function or a bound handler, and connection calls. List them by file with a count. Start a local MongoDB without Docker (mongodb-memory-server is fine) and run the test suite on the current Mongoose for a baseline; then install the target Mongoose and run it again, quoting the first error and the summary. Rewrite each call with async/await. Keep every outcome the callback produced: the same status codes, response bodies, and arguments to done or next. Each callback-style wrapper (Passport verify functions, middleware) must still call its callback exactly once. Where the old code started several operations without waiting, or could call a callback twice, choose an explicit order, and list each such place. Do not wrap Mongoose in a helper that reinstates callbacks. Target the newest Mongoose major the CI Node version supports, and say what the next major would need. Run the suite again and open a pull request with the three summaries and the list of call sites.",
  "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

A pull request that edits four source files and `package.json` with its lock file. The description opens with the call-site table, twenty-three rows grouped by file, each marked as a direct rewrite or as one of the places where ordering was made explicit. Then come three test summaries from the same tape suite: the baseline on Mongoose 6, the failing run on the new version before any edit, and the run after the port.

The two flagged functions get a paragraph each. For `generateTokens` it shows the old sequence of unawaited calls and the new one, and says which of the old calls could report an error after `done` had already been called. For the expired-token path it shows that `done` can no longer be reached twice. These are the diffs a reviewer reads closely, since the others are mechanical.

It also says what was not covered. The suite talks to the server over HTTP with superagent, so it exercises the password grant, the refresh grant and the article routes, and nothing checks a token that expires mid-test. If the pull request stops at Mongoose 8 because of Node 16, the description names the two changes that would allow 9: the `node-version` in the workflow and the base image in the `Dockerfile`.

## Run it on every dependency update that breaks on callbacks

This error is almost always introduced by a version bump, and the bump usually comes from a bot. An automation's `github` trigger never fires for a bot sender, so `pull_request.opened` will not start a run for those pull requests. Use a `webhook` trigger instead and call it from CI: add a workflow step that runs when the test job fails and its log contains `no longer accepts a callback`, and have it `POST` the branch name and the matching log lines to the trigger's URL with `Authorization: Bearer` and the trigger's secret, stored as a repository secret. That text is placed after the saved prompt as the event.

The prompt above should then say where to work: check out the branch named in the event and push the port there, or open a separate pull request against it. Send an `Idempotency-Key` header to the trigger's URL set to the head commit, so a re-run of the same failed job starts nothing new.

## Why run it on Rush?

Porting twenty-odd callbacks is easy to start and easy to get subtly wrong, because the failure mode is not a crash. A strategy that calls `done` twice, or a token that is saved before the old ones are deleted, passes a quick manual check and misbehaves under load. Finding those requires reading every call in its context and then running the real request flow against a real database on both versions. The run does that in its own sandbox, with MongoDB started for it, and keeps each command and its output in the session transcript.

It also separates what can be proven from what cannot. The pull request carries the baseline, the reproduced failure and the result after the port from one unchanged test suite, so the reviewer is comparing like with like, and it lists the paths that suite never touches. That is more than most hand-made upgrades offer, and it is what lets a reviewer merge an auth-path change they did not write.

## Frequently asked questions

### Which Mongoose version removed callbacks?

Mongoose 7. Model and query methods there return promises only and throw a `MongooseError` that says `no longer accepts a callback` when they are given a function. Mongoose 6 is the last line where both styles work, which is why the agent takes its baseline there.

### Can I just wrap the calls so callbacks keep working?

You can, with `.then(result => cb(null, result), cb)`, and it preserves the shape of the old code along with its problems. The agent uses `async` and `await` inside each handler and keeps callbacks only at the edges that require them, such as a Passport verify function. The prompt tells it not to add a compatibility helper.

### Why does the server start fine and then return 500 on every request?

The check that rejects a callback runs when the query method is called, not when the model is defined. Connecting and listening involve no such call, so startup succeeds. The first request that reaches a model method throws, and Express turns that into a 500.

### Does the agent need my production database?

No. It starts a throwaway MongoDB inside its sandbox and seeds it with the project's own script. Nothing in the request names a connection to your systems. If the tests need data the seed script does not create, the agent reports which fixtures are missing.

### Will it also fix other Mongoose 7 changes, such as strictQuery?

It reports them when the tests or the startup log surface them, and fixes those that block the suite. Changes of default behaviour that no test covers are listed in the pull request with the file they would affect, so you can decide each one.

## More Mongoose jobs

- [Fix "DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7"](https://getrush.ai/run/fix-mongoose-strictquery-deprecation-warning/mongoose/)
- [Fix "MongoParseError: options usecreateindex, usefindandmodify are not supported" in Mongoose 6 and Later](https://getrush.ai/run/fix-mongoose-usecreateindex-not-supported/mongoose/)
- [Fix useNewUrlParser Is a Deprecated Option When Upgrading Mongoose](https://getrush.ai/run/fix-usenewurlparser-is-a-deprecated-option-warning/mongoose/)

## More jobs like this: Fix a bug from an alert

- [Fix Alembic Multiple Heads After a Merge](https://getrush.ai/run/fix-multiple-heads/alembic/)
- [Fix "OSError: mysql_config not found" When Installing a Flask App's Requirements](https://getrush.ai/run/fix-mysql-config-not-found/mysqlclient/)
- [Fix Call to Undefined Function mysql_connect() on PHP 7 and PHP 8](https://getrush.ai/run/fix-mysql-connect-function-removed/php/)

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