# Add Seed Data to a Mongoose App

Yes. An agent adds an idempotent seed script to your Mongoose app that creates an admin and sample users through the model hooks, tests it, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-seed-data/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 configuration before it writes a seed, because a seed that bypasses the model's hooks stores passwords in plain text. In an API laid out like hagopj13/node-express-boilerplate, `src/models/user.model.js` defines `name`, `email` (unique, lowercased, checked with `validator.isEmail`), `password` (at least 8 characters with a letter and a digit, marked `private` so the `toJSON` plugin strips it), `role` from the `roles` list in `src/config/roles.js` (`user` and `admin`) and `isEmailVerified`, with a `pre('save')` hook that hashes a changed password with `bcryptjs` at cost 8 and an `isEmailTaken` static. `src/config/config.js` validates the environment with Joi: `NODE_ENV` must be `production`, `development` or `test`, `MONGODB_URL` and `JWT_SECRET` are required, and the test environment gets `-test` appended to the database name. `package.json` runs on `mongoose ^5.7.7`, has `faker ^5.1.0` as a dev dependency, and defines `dev`, `test`, `lint` and `coverage` scripts; there is no seed script and the README does not mention one.

The tests already contain the closest thing to a seed: `tests/fixtures/user.fixture.js` builds `userOne`, `userTwo` and `admin` with `faker.name.findName()` and `faker.internet.email()` and inserts them with `User.insertMany`, hashing the shared password itself because `insertMany` skips the `save` hook. The agent writes `src/seeds/index.js` for the development database rather than copying that file: it connects with `config.mongoose.url` and `config.mongoose.options`, refuses to run when `config.env` is `production` unless `--force` is passed, creates one admin from `SEED_ADMIN_EMAIL` and `SEED_ADMIN_PASSWORD`, and a configurable number of `user` accounts from faker, each through `User.create` so the `pre('save')` hook hashes the password. Each email is checked with `User.isEmailTaken` first, so running the script twice adds nothing, and a `--reset` flag empties the `users` and `tokens` collections first.

The configuration grows by two optional keys. `src/config/config.js` adds `SEED_ADMIN_EMAIL` and `SEED_ADMIN_PASSWORD` to the Joi schema with the same password rule the model enforces, so a weak value fails at startup rather than inside the model, and `.env.example` documents them. `package.json` gains `"seed": "cross-env NODE_ENV=development node src/seeds/index.js"`, matching how the `dev` script sets the environment. The script logs through `src/config/logger.js` rather than `console`, because `.eslintrc.json` extends `airbnb-base` and the `lint` script runs over the whole tree. `faker` stays at the installed 5.x, whose `name.findName` and `internet.email` calls the fixture already uses; moving to `@faker-js/faker` is a different pull request.

The test lives in `tests/unit/seeds/seed.test.js` and uses `tests/utils/setupTestDB.js`, which connects to the `-test` database and empties every collection before each test. It calls the exported `seed({ users: 5 })` function, asserts six documents, one with `role: 'admin'` whose `isPasswordMatch` returns true for the configured password and whose stored value is a bcrypt hash, runs `seed` again and asserts the count is unchanged, and checks that `--reset` empties the collections before inserting. The agent runs `yarn lint` and `yarn test` from its sandbox against a MongoDB it starts there, the way `docker-compose.yml` runs `mongo:4.2.1-bionic` beside the app, and keeps the output.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add seed data to this Express and Mongoose app. Read package.json, .env.example, src/config/config.js, src/config/roles.js, src/models/user.model.js, src/models/token.model.js, src/services/user.service.js, tests/fixtures/user.fixture.js, tests/utils/setupTestDB.js and .eslintrc.json first. Write src/seeds/index.js that connects with the app config, refuses to run against production without --force, creates an admin from SEED_ADMIN_EMAIL and SEED_ADMIN_PASSWORD and a number of faker users through User.create so the pre-save hook hashes passwords, skips any email that is already taken, and supports --reset. Add the two optional keys to the Joi schema and .env.example, a yarn seed script, and a test under tests/unit/seeds that seeds the test database twice and asserts the counts and the admin's hashed password. Run yarn lint and yarn test and quote the output. 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

The pull request adds `src/seeds/index.js` and `tests/unit/seeds/seed.test.js`, changes `src/config/config.js` and `.env.example` (the two optional keys), `package.json` (the `seed` script) and `README.md` (a section on running it). Its description quotes the `yarn lint` and `yarn test` output and shows the one-line command a developer runs to get an admin and sample users on a fresh database.

A reviewer runs `yarn seed` against a local MongoDB, logs in as the admin through `POST /v1/auth/login` and lists users through `GET /v1/users`, then reads the script for two things: that no code path stores a plain password, and that the production guard reads `config.env` rather than `process.env` directly, so it behaves the same way the rest of the app does. They also decide whether the seeded admin's email should be fixed or come from the environment, which the pull request leaves configurable.

The models, routes and services are unchanged. Seeding happens outside the request path, and nothing runs at startup.

## Run it on every new repository

A team that scaffolds services from this boilerplate starts a seed for each new one from its own server: a handler watches for a created repository, and sends this body to `POST /o/{org}/sessions` with that repository in `resources`. A `request_id` that is a UUID v5 of the repository's full name keeps a retried delivery from starting a second run, because the same `request_id` and body return the run already started.

A Rush automation with a `github` trigger on `pull_request.opened` can watch the same repository, but its runs are read-only: they read the branch and comment. That fits a check that the seed still runs after a model change, posting the result as a comment; the run that writes the seed is started as above.

## Why run it on Rush?

A seed is judged by two things a reviewer cannot see in a diff: whether it is safe to run twice, and whether the passwords it stores are hashed. The agent proves both by running the script against a MongoDB in its own sandbox, reading the documents back, and running the test that seeds twice, and the command output is kept with the pull request.

Every service a team builds from the same boilerplate needs the same script with its own models and roles. Starting the request once per repository gives each one a seed written against its own `user.model.js`, rather than a shared script that drifts from the schema.

## Frequently asked questions

### Why User.create and not insertMany?

`insertMany` does not run the `pre('save')` hook that hashes passwords in `user.model.js`, which is why `tests/fixtures/user.fixture.js` hashes by hand before calling it. `User.create` saves each document and runs the hook, so the seed stores bcrypt hashes without repeating the hashing code.

### Can it run in production by accident?

The script reads `config.env` and exits before connecting when it is `production`, unless `--force` is passed. The `seed` script in `package.json` sets `NODE_ENV=development` with `cross-env`, the same way the `dev` script does.

### Is the seed idempotent?

Yes. Each email is checked with the model's `isEmailTaken` static before `User.create`, so a second run adds nothing, and the test asserts that. `--reset` empties the `users` and `tokens` collections first for a clean state.

### Does it change the test fixtures?

No. `tests/fixtures/user.fixture.js` stays as it is, because the integration tests depend on its exact ids and emails. The seed is for development databases; the fixtures are for the suite.

### Which faker is used?

The `faker` 5.x already in `devDependencies`, with the same `name.findName` and `internet.email` calls the fixture uses. The pull request notes that the package is unmaintained and that `@faker-js/faker` is its successor, and leaves that upgrade to a separate change.

## More Mongoose jobs

- [Add Slow Query Logging to a Mongoose App](https://getrush.ai/run/add-slow-query-logging/mongoose/)
- [Add Soft Delete to a Mongoose Model](https://getrush.ai/run/add-soft-delete/mongoose/)
- [Add Transactions to a Mongoose App](https://getrush.ai/run/add-transactions/mongoose/)

## The same job on other stacks

- [Add a Seed Script to a Prisma Project](https://getrush.ai/run/add-seed-data/prisma/)
- [Add Seed Data to a FastAPI SQLModel App](https://getrush.ai/run/add-seed-data/sqlmodel/)
- [Write a Seed File for a Supabase Project](https://getrush.ai/run/add-seed-data/supabase/)

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