stack-mongodb
Skill0 starsChanged 5 months agoApache-2.0View on GitHub
MongoDB/Mongoose implementation patterns for agents working in projects whose docs/TECH_STACK.md lists mongodb. Load when implementing, testing, or reviewing code on this stack.
In this repository17 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- flow-adoptionSkill
- flow-legacy-migrationSkill
- stack-awsSkill
- stack-azureSkill
- stack-design-systemSkill
- stack-gcpSkill
- stack-javaSkill
- stack-kafkaSkill
- stack-natsSkill
- stack-nestjsSkill
- stack-nextjs-reactSkill
- stack-nxSkill
- stack-playwrightSkill
- stack-postgresqlSkill
- stack-quarkusSkill
- stack-react-nativeSkill
The file
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 25
Schema versioning: every document carries a schemaVersion: number field.
- Distinctive: line 26
No unbounded embedded arrays (16MB document cap).
- Very specific: line 31
Every tenant-scoped collection has tenantId (required, indexed).
- Very specific: line 32
Every compound index on a tenant-scoped collection is prefixed with tenantId: { tenantId: 1, resourceId: 1, startAt: 1 }.
- Very specific: line 36
Use mongoose-delete with { deleted, deletedAt, deletedBy } and overrideMethods: 'all' so default queries exclude deleted docs.
- Distinctive: line 43
Prefer single-document atomicity (one aggregate = one document) over transactions where the model allows — that is the Mongo-native design …
- Very specific: line 84
All rows must pass before commit per .claude/rules/LIVE_VALIDATION.md.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Stack: MongoDB (Mongoose)
Seeded from established Mongoose/NestJS best practice — this repo had no extracted source for MongoDB. Refine via repository-discovery: where the host project's
docs/DATABASE.md/docs/ARCHITECTURE.mdcontradict a default below, the generated docs win.
When this applies
Detection markers (any of):
docs/TECH_STACK.md## Detected stackslistsmongodb- Dependencies:
mongoose,@nestjs/mongoose,mongodb,mongoose-delete,mongodb-memory-server - Files:
*.schema.tsfiles with@Schema()decorators, amongo/mongodbservice indocker-compose.yml
Implementation patterns
Driver access goes through the framework's Mongo module (R-PAT-03)
- When the host framework ships a first-party Mongo integration, the repository adapter is built on that module, never the bare
mongoose/mongodbdriver wired by hand: NestJS →@nestjs/mongoose(MongooseModule.forFeature,@InjectModel); Spring → Spring Data MongoDB; Quarkus →quarkus-mongodb-panache. The module owns connection lifecycle, pooling, and DI wiring — and its test harness (e.g.Test.createTestingModule) is what the integration tests below rely on. - The injected model/handle lands in the adapter ONLY; services and domain see the abstract repository contract, nothing else. Bare
mongoose/mongodbdirectly is the fallback for a framework with no Mongo module, isolated inside the adapter. The schema/index/tenant discipline below is identical regardless of which module fronts it.
Schema discipline
- One Mongoose schema per aggregate;
@Schema({ timestamps: true })socreatedAt/updatedAtare DB-managed. - Schema versioning: every document carries a
schemaVersion: numberfield. Migrations are lazy (upgrade-on-read in the repository) or scripted batch jobs — pick per project, record the choice indocs/DATABASE.md. Never silently change a schema shape without bumping the version. - No unbounded embedded arrays (16MB document cap). Embed for ownership + bounded cardinality; reference for shared or unbounded relations.
- Repository layer owns all model access. Services never touch
Model<T>directly — same hexagonal boundary as any other adapter.
Multi-tenant via tenant field + compound indexes
MongoDB has no RLS. Tenant isolation is repository-enforced and index-backed:
- Every tenant-scoped collection has
tenantId(required, indexed). - Every compound index on a tenant-scoped collection is prefixed with
tenantId:{ tenantId: 1, resourceId: 1, startAt: 1 }. - The repository injects
tenantIdinto EVERY filter from request context. A query method without a tenant filter on a tenant-scoped collection is a review BLOCKER — there is no DB-level safety net here.
Soft delete
- Use
mongoose-deletewith{ deleted, deletedAt, deletedBy }andoverrideMethods: 'all'so default queries exclude deleted docs. - Restoration paths and "include deleted" queries are explicit (
findDeleted/findWithDeleted), never default. - Unique indexes on soft-deleted collections must be partial (
partialFilterExpression: { deleted: false }) or re-creation of a deleted entity fails.
Transactions / sessions
- Multi-document writes that must be atomic use
session.withTransaction(...); the session is passed to EVERY operation inside the unit of work, including reads that feed the write. - Transactions require a replica set — local dev and tests must run one (single-node replica set is fine; see Testing).
- Prefer single-document atomicity (one aggregate = one document) over transactions where the model allows — that is the Mongo-native design pressure.
Index discipline
- Indexes are declared in the schema (code-reviewed), not created ad hoc in production.
autoIndex: falsein production; index sync (syncIndexes()) is a deliberate deploy step.- One index per documented query pattern; expiry semantics use TTL indexes (
expireAfterSeconds) instead of application reaper loops where eventual deletion is acceptable. - Idempotency: unique index on
idempotencyKey(per tenant:{ tenantId: 1, idempotencyKey: 1 }, { unique: true }); mapE11000duplicate-key to a typed replay/conflict domain error at the adapter boundary.
Testing on this stack
- Integration tests use mongodb-memory-server (
MongoMemoryReplSetwhen transactions are exercised) — real Mongoose models against a realmongod, not mocked models. A mocked model verifies nothing about indexes, validators, or plugin behavior. - The shared discipline of
.claude/rules/TESTING_INTEGRATION.mdapplies unchanged: tests own their data (R-TESTI-04 — no seed in the test DB), tests clean up (R-TESTI-05 —deleteMany({})per touched collection inafterEach, or a fresh DB name per suite), concurrency ACs fire parallel writes (R-TESTI-02 — assert the unique index makes exactly one win). - Cross-tenant assertions are mandatory: create tenant A and B data, query as B through the repository, assert A's documents are not reachable.
- Assert index existence where an AC depends on it:
expect(await Model.collection.indexExists('tenantId_1_idempotencyKey_1')).toBe(true).
Spec validation checks
Stack-specific checks the spec validators (spec-validate-data, on SPEC_<FEATURE>.md §3 Data Model) delegate here:
| Check | Severity |
tenantId present on every tenant-scoped collection, with tenant-prefixed compound indexes | BLOCKER |
| Multi-document atomic writes: either remodeled into one aggregate/document or an explicit transaction is declared | BLOCKER |
| Soft-delete strategy stated for entities the spec marks recoverable/auditable | WARNING |
schemaVersion / migration strategy stated for shape changes to existing collections | WARNING |
| One index declared per documented query pattern; TTL index for expiry semantics | WARNING |
Idempotent endpoints have a unique idempotencyKey index | WARNING |
| Orphan-cleanup strategy explicit for references (no FK cascade exists in MongoDB) | WARNING |
Live validation commands
R-VAL-02 matrix adapted to MongoDB — exact invocations live in docs/DEV_SETUP.md; obligations:
| Check | Typical shape |
| Boot the app against a fresh DB; schema/index definitions must register cleanly | dev target per DEV_SETUP |
| Verify indexes materialize | mongosh --eval 'db.<coll>.getIndexes()' (or the project's DB MCP tool when docs/DEV_SETUP.md declares one) |
| Run the seed (multi-tenant, all entity states) | seed target per DEV_SETUP |
| Smoke-query the new shape | mongosh findOne against the new collection |
| Run integration tests (mongodb-memory-server) | affected test target per DEV_SETUP |
All rows must pass before commit per .claude/rules/LIVE_VALIDATION.md.
Introspection (database-validator)
The data-dictionary refresh (docs/DATABASE.md) reads ONLY the live DB — Mongoose schemas are the declared shape, not the truth:
| What | Read command |
| Collections + options/validator rules | db.getCollectionInfos() |
| Indexes per collection | db.<coll>.getIndexes() — verify tenant-prefixed compounds, TTL, unique idempotency keys |
| Actual document shape | aggregate([{$sample:{size:N}}]) and project field names/types — compare against the declared schema |
| Schema versions in the wild | db.<coll>.distinct('schemaVersion') |
For this engine docs/DATABASE.md documents collections, field shapes, indexes, and validator rules in place of tables/columns/constraints.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

