Mongoose (MongoDB)
Purpose
Express the approved document design (document-schema-design) through Mongoose: schemas that actually validate, deliberate indexes, efficient reads, and middleware that doesn't hide business logic.
When to Use
- After MongoDB + Mongoose were approved (
database-selection).
- Not for document design decisions (upstream) or relational projects.
Inputs
- Approved document design: collection shapes, embed/reference map, duplication ledger, validation requirements.
- Hot query paths + index needs (
indexing).
Discovery Questions
- Which parts of each document are stable core (strict schema) vs the designed variable region (
Schema.Types.Mixed/subdocument maps — scoped, not global)?
- Which queries are hot and read-only (lean candidates)?
- Any cross-document invariants needing sessions/transactions (
transactions) — and are they rare enough to stay MongoDB-shaped?
Responsibilities
- Define schemas mirroring the approved design: required fields, types, enums, match/min/max validators on the stable core; the variable region explicitly scoped — strict mode on, unknown paths rejected elsewhere.
- Model embed vs reference exactly as designed: subdocument schemas for embeds;
ObjectId refs + deliberate populate policy for references (populate is a query per path — hot paths get explicit shaping or aggregation instead).
- Declare indexes in the schema to match
indexing's plan — but control build timing in production (autoIndex off; builds via migration/ops step — database-migrations for index rollouts on big collections).
- Set query discipline:
.lean() for read-only paths (hydration costs), projections scoped to need, cursor pagination on stable keys, maxTimeMS on heavy queries.
- Keep middleware (hooks) thin: derived-field maintenance, timestamps — not business rules (those live in services,
../../backend/backend-api-architecture); document every hook (hidden write amplification).
- Use sessions/transactions only for the flagged cross-document invariants; single-document atomicity is the default model.
- Enforce the duplication ledger: propagation updates implemented where the design assigned ownership.
- Version/migrate shapes deliberately: schema changes to live collections go through
data-migration (backfills), not silent shape drift.
Required Workflow
- Translate collection designs into schemas; strict core + scoped variable regions.
- Express embed/reference exactly per design; set populate/aggregation policy per hot path.
- Declare indexes; plan production build strategy.
- Set lean/projection/pagination/timeout conventions.
- Implement duplication-propagation where owned; wire flagged transactions.
- Verify validation rejects malformed documents (tests) and unknown fields.
Decision Rules
- Strict mode stays on;
Mixed appears only where the design named a variable region.
populate chains on list endpoints are the Mongo N+1 — restructure (embed, aggregate, or batched fetch) when a hot path grows them.
- Validation in Mongoose complements collection-level JSON Schema (defense at the DB when the design requires it) — Mongoose-only validation vanishes for any non-Mongoose writer.
- If transactions become routine rather than exceptional, the domain may be relational — escalate to
database-selection, don't normalize the pain.
Rules
- No business logic in hooks; hooks documented.
- Index changes follow the
indexing plan — no ad-hoc index: true sprinkling.
- Shape changes to existing collections ship with their backfill (
data-migration).
Anti-Patterns
strict: false / Mixed-everywhere schemas ("flexible").
- Populate pyramids on hot list endpoints.
- autoIndex building indexes on production at boot.
- Hydrated full documents where
.lean() + projection serves.
- Hooks that send emails or mutate other collections invisibly.
- Silent schema drift with no backfill — three shapes of the same collection in production.
Validation Checklist
Definition of Done
The approved document design expressed as strict, validated Mongoose schemas with deliberate population/index/lean discipline, owned duplication propagation, and exceptional-only transactions — with malformed-document rejection proven by tests.
Related Skills
database-selection, document-schema-design, indexing, transactions, concurrency, data-migration, database-performance, database-security, seed-data.
Related Knowledge
../../../knowledge/ (variable regions, duplication ledger).
Related References
../../../references/database/mongoose/ (patterns, when populated).
Context Loading Guidance
- Requires: approved document design, hot paths, index plan.
- Does not require: re-deciding embed/reference, app feature code.
- May load:
indexing, data-migration (shape changes).
- Stop when: schemas + conventions + propagation are recorded/implemented.
Token Efficiency Guidance
Work per collection from the design table; show one schema exemplar, not all of them. The populate-policy list per hot path is the high-value artifact.
1---2name: mongoose-mongodb3description: Use to plan Mongoose over MongoDB — expressing the approved document design as schemas with real validation, indexes declared and built deliberately, lean queries, middleware discipline, and transactions only where the design demands them.4---56# Mongoose (MongoDB)78## Purpose910Express the approved document design (`document-schema-design`) through Mongoose: schemas that actually validate, deliberate indexes, efficient reads, and middleware that doesn't hide business logic.1112## When to Use1314- After MongoDB + Mongoose were approved (`database-selection`).15- **Not** for document design decisions (upstream) or relational projects.1617## Inputs1819- Approved document design: collection shapes, embed/reference map, duplication ledger, validation requirements.20- Hot query paths + index needs (`indexing`).2122## Discovery Questions2324- Which parts of each document are stable core (strict schema) vs the designed variable region (`Schema.Types.Mixed`/subdocument maps — scoped, not global)?25- Which queries are hot and read-only (lean candidates)?26- Any cross-document invariants needing sessions/transactions (`transactions`) — and are they rare enough to stay MongoDB-shaped?2728## Responsibilities2930- Define schemas mirroring the approved design: required fields, types, enums, match/min/max validators on the stable core; the variable region **explicitly scoped** — strict mode on, unknown paths rejected elsewhere.31- Model embed vs reference exactly as designed: subdocument schemas for embeds; `ObjectId` refs + deliberate `populate` policy for references (populate is a query per path — hot paths get explicit shaping or aggregation instead).32- Declare **indexes in the schema** to match `indexing`'s plan — but control build timing in production (autoIndex off; builds via migration/ops step — `database-migrations` for index rollouts on big collections).33- Set query discipline: `.lean()` for read-only paths (hydration costs), projections scoped to need, cursor pagination on stable keys, `maxTimeMS` on heavy queries.34- Keep **middleware (hooks) thin**: derived-field maintenance, timestamps — not business rules (those live in services, `../../backend/backend-api-architecture`); document every hook (hidden write amplification).35- Use **sessions/transactions** only for the flagged cross-document invariants; single-document atomicity is the default model.36- Enforce the duplication ledger: propagation updates implemented where the design assigned ownership.37- Version/migrate shapes deliberately: schema changes to live collections go through `data-migration` (backfills), not silent shape drift.3839## Required Workflow40411. Translate collection designs into schemas; strict core + scoped variable regions.422. Express embed/reference exactly per design; set populate/aggregation policy per hot path.433. Declare indexes; plan production build strategy.444. Set lean/projection/pagination/timeout conventions.455. Implement duplication-propagation where owned; wire flagged transactions.466. Verify validation rejects malformed documents (tests) and unknown fields.4748## Decision Rules4950- Strict mode stays on; `Mixed` appears only where the design named a variable region.51- `populate` chains on list endpoints are the Mongo N+1 — restructure (embed, aggregate, or batched fetch) when a hot path grows them.52- Validation in Mongoose complements collection-level JSON Schema (defense at the DB when the design requires it) — Mongoose-only validation vanishes for any non-Mongoose writer.53- If transactions become routine rather than exceptional, the domain may be relational — escalate to `database-selection`, don't normalize the pain.5455## Rules5657- No business logic in hooks; hooks documented.58- Index changes follow the `indexing` plan — no ad-hoc `index: true` sprinkling.59- Shape changes to existing collections ship with their backfill (`data-migration`).6061## Anti-Patterns6263- `strict: false` / Mixed-everywhere schemas ("flexible").64- Populate pyramids on hot list endpoints.65- autoIndex building indexes on production at boot.66- Hydrated full documents where `.lean()` + projection serves.67- Hooks that send emails or mutate other collections invisibly.68- Silent schema drift with no backfill — three shapes of the same collection in production.6970## Validation Checklist7172- [ ] Schemas mirror the design; strict core, scoped variable regions.73- [ ] Embed/reference + populate/aggregation policy per hot path.74- [ ] Indexes declared per plan; production build strategy set.75- [ ] lean/projection/pagination/timeout conventions recorded.76- [ ] Duplication propagation implemented per ledger.77- [ ] Transactions only where flagged; validation tests reject malformed/unknown.7879## Definition of Done8081The approved document design expressed as strict, validated Mongoose schemas with deliberate population/index/lean discipline, owned duplication propagation, and exceptional-only transactions — with malformed-document rejection proven by tests.8283## Related Skills8485`database-selection`, `document-schema-design`, `indexing`, `transactions`, `concurrency`, `data-migration`, `database-performance`, `database-security`, `seed-data`.8687## Related Knowledge8889`../../../knowledge/` (variable regions, duplication ledger).9091## Related References9293`../../../references/database/mongoose/` (patterns, when populated).9495## Context Loading Guidance9697- **Requires:** approved document design, hot paths, index plan.98- **Does not require:** re-deciding embed/reference, app feature code.99- **May load:** `indexing`, `data-migration` (shape changes).100- **Stop when:** schemas + conventions + propagation are recorded/implemented.101102## Token Efficiency Guidance103104Work per collection from the design table; show one schema exemplar, not all of them. The populate-policy list per hot path is the high-value artifact.