# Add Soft Delete to a Mongoose Model

Yes. An agent adds a soft-delete plugin to your Mongoose models that sets deletedAt, hides deleted documents from queries, updates tests, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-soft-delete/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 model and the plugins it already uses, because soft delete is a plugin in this codebase, not a field. In an API like hagopj13/node-express-boilerplate, `package.json` depends on `mongoose` ^5.7.7 (5.13.20 in `yarn.lock`), `express` ^4.17.1 and `jest` ^26 with `supertest` and `faker` for tests, and runs `jest -i --colors --verbose --detectOpenHandles`. `src/models/user.model.js` defines `name`, `email`, `password` (marked `private: true`), `role` and `isEmailVerified` with `timestamps: true`, applies `toJSON` and `paginate` from `src/models/plugins/`, and has an `isEmailTaken` static built on `findOne({ email, _id: { $ne: excludeUserId } })`. `toJSON.plugin.js` strips every path marked `private` plus `__v` and the timestamps; `paginate.plugin.js` runs `countDocuments(filter)` and `find(filter)` with sort, skip, limit and populate. `src/services/user.service.js` deletes with `user.remove()`, and `user.controller.js` answers 204.

The agent writes `src/models/plugins/softDelete.plugin.js` in the style of the two existing plugins. It adds a `deletedAt` path of type `Date`, default `null`, marked `private: true` so the existing `toJSON` plugin keeps it out of responses without a second transform. It adds a `softDelete()` document method that sets the timestamp and saves, and a `restore()` that clears it. Query middleware on `find`, `findOne`, `countDocuments`, `findOneAndUpdate`, `updateOne` and `updateMany` adds `deletedAt: null` to the filter unless the query carries a `withDeleted: true` option, so `findById`, `paginate` and `isEmailTaken` all exclude deleted documents with no change to their code. The plugin is exported from `plugins/index.js` and applied to `userSchema`; `tokenSchema` keeps hard deletes, since a refresh token is not user data worth keeping.

Then the agent follows the consequences through the services. `deleteUserById` calls `user.softDelete()` instead of `user.remove()`, and the controller still answers 204. `isEmailTaken` now ignores deleted users, but the schema's `unique: true` on `email` is a MongoDB index that does not, so a sign-up with a deleted user's address would pass the check and then fail on the index with a duplicate-key error that surfaces as 500 instead of the 400 `Email already taken` the API promises. The agent makes `isEmailTaken` query with `withDeleted: true` so the answer stays correct, and writes the policy question in the pull request: free the address by anonymising it on delete, or keep it reserved, which is what the unique index does today.

Tests follow the two patterns in the repository. `tests/unit/models/plugins/softDelete.plugin.test.js` defines its own schema with the plugin, like `paginate.plugin.test.js` does, and covers that `find` and `countDocuments` hide a soft-deleted document, that `withDeleted` shows it, that `restore` brings it back, and that `toJSON` omits `deletedAt`. In `tests/integration/user.test.js` the `DELETE /v1/users/:userId` cases that asserted `User.findById` returns `null` are changed to read the document with `withDeleted` and assert `deletedAt` is set, and a new case asserts a deleted user no longer appears in `GET /v1/users`. The suite needs MongoDB, which the sandbox does not have as a service, so the agent adds `mongodb-memory-server` as a dev dependency and has `tests/utils/setupTestDB.js` start one when `MONGODB_URL` is unset, leaving the `.env` path unchanged. It runs `yarn lint` and `yarn test`.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add soft delete to the User model of this Express and Mongoose application. 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/models/plugins/paginate.plugin.js, src/models/plugins/index.js, src/services/user.service.js, src/services/auth.service.js, src/controllers/user.controller.js, tests/utils/setupTestDB.js, tests/unit/models/plugins/paginate.plugin.test.js and tests/integration/user.test.js first. Write src/models/plugins/softDelete.plugin.js that adds a private deletedAt date, softDelete and restore document methods, and query middleware on find, findOne, countDocuments, findOneAndUpdate, updateOne and updateMany that excludes deleted documents unless the query has a withDeleted option. Apply it to the user schema only. Change deleteUserById to soft delete, and make isEmailTaken check with withDeleted so the unique index on email cannot produce a 500; explain the address-reuse policy question in the pull request. Write a plugin unit test in the style of the paginate test and update the integration tests for DELETE and list. If MongoDB is not available, add mongodb-memory-server as a dev dependency and start it from setupTestDB when MONGODB_URL is unset. Run yarn lint and yarn test and open a pull request.",
  "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 adds `softDelete.plugin.js` and its test, changes `user.model.js`, `plugins/index.js`, `user.service.js`, `tests/integration/user.test.js`, `tests/utils/setupTestDB.js`, `package.json` and `yarn.lock`. The description explains which queries now exclude deleted documents and how to opt out, states that `DELETE` still answers 204 and that responses never include `deletedAt`, and sets out the email-reuse question with the unique index as the reason it exists.

The run's record keeps the `yarn lint` and `yarn test` output, so a reviewer sees ESLint with the Airbnb, Jest and security rule sets pass and the integration suite run against a real MongoDB, including the changed `DELETE` cases.

Before merging, a reviewer decides the email policy, whether the admin API needs a `GET` that lists deleted users or a restore route, and whether any aggregation pipelines elsewhere in the codebase need their own `deletedAt` match, since Mongoose query middleware does not apply to `aggregate`.

## Run it on every Node.js service repository

A team with several services on this boilerplate starts one run per repository from its own server: a `POST /o/{org}/sessions` each, with that 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 rather than opening a second pull request. Each run starts its own MongoDB in its own sandbox.

Afterwards, an automation on the Project with a `github` trigger on `pull_request.opened` and the prompt "if this pull request adds a Mongoose query that should see deleted users, or an aggregate on the users collection, comment on whether it needs withDeleted or a deletedAt match" reviews each change against the new rule. The trigger adds the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

Soft delete is a cross-cutting change: the plugin is small, but every query, index and test that touched deletion has to be read to know what else moved. The agent does that reading in its own sandbox against the real suite, finds the unique index that turns a passing check into a 500, and brings a MongoDB up to prove the result rather than reason about it.

Every command's output stays with the run, so a reviewer reads the passing lint and the integration results rather than the description. Several services can get the same plugin at once, each on its own machine with its own record.

## Frequently asked questions

### Will deleted users still show up in paginate or findById?

No. `paginate` calls `countDocuments` and `find`, and `findById` is `findOne`; all three carry the plugin's query middleware, which adds `deletedAt: null` unless the query sets `withDeleted`. No change to those call sites is needed.

### What happens if someone signs up with a deleted user's email?

Today the unique index on `email` rejects it at the database. With soft delete, `isEmailTaken` is made to look at deleted users too, so the API keeps answering 400 `Email already taken` instead of a 500 from the index. Freeing the address would mean anonymising it on delete, which the pull request raises as a decision rather than making it.

### Does deletedAt appear in API responses?

No. The path is marked `private: true`, and the repository's existing `toJSON` plugin strips every private path, the same way it already hides `password`.

### Why not soft-delete tokens as well?

Refresh tokens in `token.model.js` are removed on logout and have no value after that; keeping them would only grow the collection. The plugin is applied to the user schema only, and the pull request says so.

## More Mongoose jobs

- [Add Transactions to a Mongoose App](https://getrush.ai/run/add-transactions/mongoose/)
- [Add Two-Factor Authentication to an Express and Mongoose API](https://getrush.ai/run/add-two-factor-auth/mongoose/)
- [Fix "Model.find() no longer accepts a callback" After a Mongoose Upgrade](https://getrush.ai/run/fix-mongoose-callback-error/mongoose/)

## The same job on other stacks

- [Add Soft Delete to a Prisma Schema](https://getrush.ai/run/add-soft-delete/prisma/)
- [Add Soft Delete to a Quarkus Panache Entity](https://getrush.ai/run/add-soft-delete/quarkus/)
- [Add Soft Delete to Sequelize Models in an Express App](https://getrush.ai/run/add-soft-delete/sequelize/)

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