agentleFS
isabelle-barpisabelle-barp/agent-brain/skills/stack-mongodb/SKILL.md

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.

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
  1. Very specific:

    Schema versioning: every document carries a schemaVersion: number field.

    line 25
  2. Distinctive:

    No unbounded embedded arrays (16MB document cap).

    line 26
  3. Very specific:

    Every tenant-scoped collection has tenantId (required, indexed).

    line 31
  4. Very specific:

    Every compound index on a tenant-scoped collection is prefixed with tenantId: { tenantId: 1, resourceId: 1, startAt: 1 }.

    line 32
  5. Very specific:

    Use mongoose-delete with { deleted, deletedAt, deletedBy } and overrideMethods: 'all' so default queries exclude deleted docs.

    line 36
  6. Distinctive:

    Prefer single-document atomicity (one aggregate = one document) over transactions where the model allows — that is the Mongo-native design …

    line 43
  7. Very specific:

    All rows must pass before commit per .claude/rules/LIVE_VALIDATION.md.

    line 84

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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.md contradict a default below, the generated docs win.

When this applies

Detection markers (any of):

  • docs/TECH_STACK.md ## Detected stacks lists mongodb
  • Dependencies: mongoose, @nestjs/mongoose, mongodb, mongoose-delete, mongodb-memory-server
  • Files: *.schema.ts files with @Schema() decorators, a mongo/mongodb service in docker-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/mongodb driver 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/mongodb directly 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 }) so createdAt/updatedAt are DB-managed.
  • Schema versioning: every document carries a schemaVersion: number field. Migrations are lazy (upgrade-on-read in the repository) or scripted batch jobs — pick per project, record the choice in docs/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 tenantId into 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-delete with { deleted, deletedAt, deletedBy } and overrideMethods: '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: false in 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 }); map E11000 duplicate-key to a typed replay/conflict domain error at the adapter boundary.

Testing on this stack

  • Integration tests use mongodb-memory-server (MongoMemoryReplSet when transactions are exercised) — real Mongoose models against a real mongod, not mocked models. A mocked model verifies nothing about indexes, validators, or plugin behavior.
  • The shared discipline of .claude/rules/TESTING_INTEGRATION.md applies unchanged: tests own their data (R-TESTI-04 — no seed in the test DB), tests clean up (R-TESTI-05 — deleteMany({}) per touched collection in afterEach, 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:

CheckSeverity
tenantId present on every tenant-scoped collection, with tenant-prefixed compound indexesBLOCKER
Multi-document atomic writes: either remodeled into one aggregate/document or an explicit transaction is declaredBLOCKER
Soft-delete strategy stated for entities the spec marks recoverable/auditableWARNING
schemaVersion / migration strategy stated for shape changes to existing collectionsWARNING
One index declared per documented query pattern; TTL index for expiry semanticsWARNING
Idempotent endpoints have a unique idempotencyKey indexWARNING
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:

CheckTypical shape
Boot the app against a fresh DB; schema/index definitions must register cleanlydev target per DEV_SETUP
Verify indexes materializemongosh --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 shapemongosh 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:

WhatRead command
Collections + options/validator rulesdb.getCollectionInfos()
Indexes per collectiondb.<coll>.getIndexes() — verify tenant-prefixed compounds, TTL, unique idempotency keys
Actual document shapeaggregate([{$sample:{size:N}}]) and project field names/types — compare against the declared schema
Schema versions in the wilddb.<coll>.distinct('schemaVersion')

For this engine docs/DATABASE.md documents collections, field shapes, indexes, and validator rules in place of tables/columns/constraints.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.