Skip to content
Development
Skill

/api-database-mongoose

MongoDB ODM with schemas, validation, middleware, and TypeScript support

From plugin
skills
26200 skills

Claude Code

$ npx -y skills add agents-inc/skills --skill api-database-mongoose --agent claude-code

SKILL.md

api-database-mongoose.SKILL.md
name: api-database-mongoose
description: MongoDB ODM with schemas, validation, middleware, and TypeScript support

Mongoose ODM Patterns

> **Quick Guide:** Use Mongoose as the ODM layer for MongoDB. Let TypeScript infer types from schema definitions instead of duplicating interfaces. Register all middleware before calling `model()` -- hooks added after compilation are silently ignored. Use `.lean()` for any read-only query. Pass `{ session }` to every operation inside a transaction or enable `transactionAsyncLocalStorage`. Prefer `session.withTransaction()` over manual commit/abort. Use `127.0.0.1` instead of `localhost` in connection strings (Node.js 18+ IPv6 preference causes timeouts).

---

<critical_requirements>

CRITICAL: Before Using This Skill

**(You MUST define all middleware (pre/post hooks) BEFORE calling `model()` -- hooks registered after model compilation are silently ignored with no error)**

**(You MUST pass `{ session }` to EVERY operation inside a transaction -- missing session causes that operation to run outside the transaction silently)**

**(You MUST use `.lean()` for read-only queries returning API responses -- skipping lean wastes 3x memory on hydration overhead)**

**(You MUST use `127.0.0.1` instead of `localhost` in connection strings -- Node.js 18+ prefers IPv6 and `localhost` causes connection timeouts)**

**(You MUST NOT use `findOneAndUpdate`/`updateOne` and expect `pre('save')` to fire -- only `save()` and `create()` trigger document middleware)**

**(You MUST NOT use `next()` callbacks in pre hooks on Mongoose 9 -- use async/await instead; `next()` was removed in v9)**

</critical_requirements>

---

**Auto-detection:** Mongoose, mongoose, mongoose.connect, Schema, model, ObjectId, populate, HydratedDocument, InferSchemaType, InferRawDocType, pre('save'), post('save'), lean, mongoose.startSession, withTransaction, discriminator, virtual, Schema.Types.ObjectId, Types.ObjectId

**When to use:**

  • Defining MongoDB schemas and models with Mongoose
  • TypeScript integration with schema type inference
  • Middleware hooks (pre/post save, validate, find, delete)
  • Population (resolving references between collections)
  • Transactions with session management
  • Virtuals and instance/static methods
  • Discriminators (single collection inheritance)
  • Connection management (single and multi-database)

**Key patterns covered:**

  • Schema definition with automatic TypeScript inference
  • TypeScript typing (HydratedDocument, InferSchemaType, methods/statics/virtuals generics)
  • CRUD operations (create, find, update, delete, lean vs hydrated)
  • Middleware hooks and their execution rules
  • Population with field selection and limits
  • Transactions (withTransaction, transactionAsyncLocalStorage)
  • Validation (built-in validators, custom validators, error messages)
  • Virtuals (computed, populate virtuals)
  • Discriminators (inheritance pattern)
  • Connection setup and multi-database

**When NOT to use:**

  • Raw MongoDB driver queries without schema enforcement (use the native driver)
  • Relational data with complex joins and foreign key constraints (use a relational database)
  • Simple key-value storage (use a dedicated key-value store)

**Detailed Resources:**

  • For decision frameworks, quick reference tables, and migration notes, see [reference.md](reference.md)

**Core Patterns:**

  • [examples/core.md](examples/core.md) -- Connection, schema definition, TypeScript typing, model creation, CRUD, validation

**Middleware & Lifecycle:**

  • [examples/middleware.md](examples/middleware.md) -- Pre/post hooks, error handling middleware, query middleware, soft delete

**Relationships & Population:**

  • [examples/population.md](examples/population.md) -- Populate, virtual populate, discriminators, embedding vs referencing

**Transactions & Advanced:**

  • [examples/transactions.md](examples/transactions.md) -- Sessions, withTransaction, transactionAsyncLocalStorage, connection management

---

<philosophy>

Philosophy

Mongoose provides schema-based modeling for MongoDB. Its value is the **application-layer enforcement** of structure, validation, middleware, and type safety on top of MongoDB's flexible document model.

**Core principles:**

1. **Schema-first** -- Define schemas before models. Schemas enforce structure, validation, defaults, and middleware at the application layer. 2. **Infer, don't duplicate** -- Let Mongoose infer TypeScript types from schema definitions. Only define explicit interfaces when adding methods, statics, or virtuals. 3. **Middleware before model** -- All pre/post hooks must be registered before `model()`. This is the single most common Mongoose bug -- hooks added after compilation are silently ignored. 4. **Lean for reads** -- `.lean()` returns plain JavaScript objects (3x less memory). Use it for every read-only query. Only skip lean when you need Mongoose document methods. 5. **Session discipline** -- Every operation inside a transaction must receive `{ session }`. One missed session means that operation runs outside the transaction with no error. 6. **Validate at the schema** -- Push validation into schema definitions (required, min, max, enum, custom validators with error messages). Don't validate in application code what the schema can enforce.

**When to use Mongoose:**

  • You want schema enforcement and validation on MongoDB documents
  • You need middleware hooks (pre/post save, validate, find)
  • You want automatic TypeScript type inference from schemas
  • You need population (reference resolution between collections)
  • You want computed properties (virtuals) and instance methods

**When NOT to use Mongoose:**

  • Performance-critical bulk operations where the ODM overhead matters (use native driver)
  • You only need raw MongoDB queries without schema enforcement
  • You're doing heavy aggregation-only workloads (aggregation pipelines bypass most Mongoose features)

</philosophy>

---

<patterns>

Core Patterns

Pattern 1: Connection S

Read more
@agents-inc
Ships withskills

The official skills marketplace for Agents Inc. 230+ skills covering everything from React and Prisma to Redis, ElevenLabs, and infrastructure tooling. Pick the skills that match your stack and install them via Claude Code. Need more control?

Stars on GitHub

Momentum

stars in total
26
Star history of agents-inc/skills on GitHub, a chart by star-history.com

Other skills on skills.

ai-infrastructure-litellm

ai-infrastructure-lite…

LiteLLM proxy server setup, TypeScript client patterns via OpenAI SDK, model routing, fallbacks, load balancing, spend tracking,…

@agents-inc@agents-incInstall Skill
ai-infrastructure-modal

ai-infrastructure-moda…

Serverless GPU compute platform for AI model deployment — web endpoints, GPU functions, model serving, and TypeScript client…

@agents-inc@agents-incInstall Skill
ai-infrastructure-ollama

ai-infrastructure-olla…

Local LLM inference with the Ollama JavaScript client -- chat, streaming, tool calling, vision, embeddings, structured output,…

@agents-inc@agents-incInstall Skill

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or…

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills10d309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android — semantic ARIA roles and labels,…

ecc12d293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commits…

react1d252k
@facebook@facebookInstall Skill

Questions about api-database-mongoose.

Which coding agents can use api-database-mongoose?
api-database-mongoose installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.