# Add Optimistic Locking to a Mongoose API

Yes. An agent turns on Mongoose's optimistic concurrency, exposes the document version, rejects stale updates with 409, tests the race and opens a PR.

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

## What the agent does

The agent reads the update path end to end. In an app laid out like hagopj13/node-express-boilerplate, `src/routes/v1/user.route.js` wires `PATCH /:userId` through `auth('manageUsers')`, `validate(userValidation.updateUser)` and `userController.updateUser`; `src/validations/user.validation.js` allows `email`, `password` and `name` in the body with `.min(1)`; and `src/services/user.service.js` implements `updateUserById` as `getUserById`, an email check, `Object.assign(user, updateBody)` and `user.save()`. `src/models/user.model.js` declares the schema with `timestamps: true` and the `toJSON` and `paginate` plugins, and `src/models/plugins/toJSON.plugin.js` deletes `__v`, `createdAt` and `updatedAt` from every serialized document and renames `_id` to `id`. `package.json` asks for `mongoose ^5.7.7`, which `yarn.lock` resolves to `5.13.20`, tests with `jest 26.6.3` and `supertest 6.1.3` against a real MongoDB through `tests/utils/setupTestDB.js`, and `.travis.yml` runs `yarn lint` and `yarn test` on Node 12 with a `mongodb` service.

Mongoose has had the mechanism since `5.10.0`, whose changelog entry adds the `optimisticConcurrency` schema option so that `save()` checks the version it loaded. The default `versionKey` behaviour only guards array changes; with the option on, a `save()` of a document whose `__v` has moved since `findById` throws a `VersionError`. The agent sets `optimisticConcurrency: true` on the user schema and leaves the token schema alone, since tokens are only created and deleted. Update queries such as `findOneAndUpdate` do not bump the version, and the agent greps the services to confirm every write to users goes through `save()`: `createUser`, `updateUserById` and the two callers in `auth.service.js` (`resetPassword` and `verifyEmail`) all do.

A client cannot send back a version it never saw, so the serializer changes. The `toJSON` plugin stops deleting `__v` and renames it to `version`, and the `User` schema in `src/docs/components.yml` gains the field. The PATCH validation accepts an optional integer `version`; when it is present, `updateUserById` compares it with the loaded document's `__v` before assigning and throws `ApiError(409, 'User was modified by someone else')` on a mismatch. The `save()` still runs under the schema option for the window between the read and the write. `src/middlewares/error.js` currently turns any `mongoose.Error` into a 400, which would make a `VersionError` read like bad input, so `errorConverter` gets an explicit branch mapping `mongoose.Error.VersionError` to 409 before the generic one.

The tests follow the suite's conventions. `tests/unit/models/plugins/toJSON.plugin.test.js` has a case named `should remove __v` that now asserts the rename, and `tests/integration/user.test.js` compares PATCH responses with `toEqual` against an exact object, so each of those expectations gains `version`. New integration cases send a stale `version` and expect 409, load one user twice with `User.findById`, save the first copy, save the second and expect the 409 from the converter, and send no `version` at all and expect the old behaviour, since `auth.service.js` and existing clients never send one. The agent runs `yarn lint` (airbnb-base with prettier) and `yarn test` against a MongoDB it starts in the sandbox, as `setupTestDB` expects at `MONGODB_URL`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add optimistic locking to the user model of this Express and Mongoose API. Read package.json, yarn.lock for the resolved mongoose version, src/models/user.model.js, src/models/token.model.js, src/models/plugins/toJSON.plugin.js, src/services/user.service.js, src/services/auth.service.js, src/controllers/user.controller.js, src/routes/v1/user.route.js, src/validations/user.validation.js, src/middlewares/error.js, src/docs/components.yml, tests/unit/models/plugins/toJSON.plugin.test.js, tests/integration/user.test.js, tests/utils/setupTestDB.js and .travis.yml first. Set optimisticConcurrency: true on the user schema. Change the toJSON plugin to expose __v as version instead of deleting it, update the swagger User schema, accept an optional integer version in the PATCH body validation, and in updateUserById answer 409 when the sent version differs from the loaded document's __v. Map mongoose VersionError to 409 in errorConverter. Update the existing toEqual expectations, add integration tests for a stale version, a concurrent save and a request with no version, run yarn lint and yarn test against a local MongoDB, and open a pull request that quotes 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 changes `src/models/user.model.js`, `src/models/plugins/toJSON.plugin.js`, `src/validations/user.validation.js`, `src/services/user.service.js`, `src/middlewares/error.js`, `src/docs/components.yml` and the two test files, and adds the three integration cases. Its description quotes the `jest` output and shows the 409 body for a stale update as the API returns it, with the `code` and `message` fields the existing `errorHandler` produces.

A reviewer checks that no write to users bypasses `save()` (an `updateOne` added later would skip the version check silently), that API clients can tolerate the new `version` field in every user response, and whether the compare-before-assign should be mandatory for some callers rather than optional. The agent keeps it optional so `auth.service.js` and current clients keep working, and says so in the README section it adds under Custom Mongoose Plugins.

Nothing changes for a client that never sends `version`: the request goes through as before, and only a genuine overlap between two writers is refused.

## Run it on every Linear issue labelled concurrency

An automation on the Project with a `linear` trigger on `linear.issue.labeled`, `labels` set to `concurrency` and the state in `plan` mode starts a read-only run that reads the issue and the repository and posts its plan as a comment on the issue: which models write through `save()`, which use update queries, and what the version field would change in the API. The trigger adds the issue after the prompt and fills in no placeholder.

When the plan is agreed, a handler on your own server sends this body to `POST /o/{org}/sessions` with the issue's URL as a second entry in `resources` (`https://linear.app/<workspace>/issue/<ID>`), so the run reads it through your Linear connection, and a `request_id` that is a UUID v5 of the issue id so a second label event returns the run already started. That run opens the pull request and the key's `webhook_url` receives `run.completed` with its link.

## Why run it on Rush?

A race is the one bug a unit test with a mocked model cannot show. The agent runs the integration suite against a real MongoDB in its sandbox, loads the same document twice, saves both copies and keeps the `VersionError` and the 409 it became in the run's record, so a reviewer reads the actual failure rather than trusting that the schema option does what the docs say.

The same three-part change (schema option, exposed version, 409 mapping) is owed by every Mongoose service that updates documents with read-modify-write, and each has its own serializer and error converter to adjust. One run per repository reads that service's plugins and tests and opens one pull request each, with the same status code and field name across all of them.

## Frequently asked questions

### Why 409 and not 400 or 412?

The request was well formed; it lost to another writer, which is what Conflict means. `412 Precondition Failed` is right when the client uses `If-Match` with an ETag; this app sends the version in the JSON body alongside the fields, so the agent uses 409 and names the reason in the message.

### Does the version check cover findOneAndUpdate?

No. Mongoose updates the version key only on `save()`, and `optimisticConcurrency` guards `save()` only. The agent checks that every write to users in the services goes through `save()` and notes in the README that an update query added later would skip the check.

### Why expose __v at all?

A client can only send back a version it has seen. The `toJSON` plugin deleted `__v` from every response, so no client could do optimistic updates even with the schema option on. Renaming it to `version` keeps the API free of Mongoose internals while giving clients the number.

### Will existing clients break?

No. The `version` field is optional on PATCH, and a request without it behaves as before. Responses gain one integer field; a client that validates response shapes strictly needs to allow it.

### What about the token model?

Tokens are created and deleted, never updated in place, so there is no lost update to prevent. The agent leaves that schema alone and says why in the pull request.

## More Mongoose jobs

- [Add Request ID Logging to an Express and Mongoose API](https://getrush.ai/run/add-request-id-logging/mongoose/)
- [Add Seed Data to a Mongoose App](https://getrush.ai/run/add-seed-data/mongoose/)
- [Add Slow Query Logging to a Mongoose App](https://getrush.ai/run/add-slow-query-logging/mongoose/)

## The same job on other stacks

- [Add Optimistic Locking to Prisma Models](https://getrush.ai/run/add-optimistic-locking/prisma/)
- [Add Optimistic Locking to a Sequelize App](https://getrush.ai/run/add-optimistic-locking/sequelize/)
- [Add Optimistic Locking to SQLModel Updates](https://getrush.ai/run/add-optimistic-locking/sqlmodel/)

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