jpskill.com
🛠️ 開発・MCP コミュニティ

api-database-mongodb

Mongooseを使ってMongoDBのスキーマ定義、モデル作成、クエリ実行、集計、インデックス設定、TypeScript型付け、接続管理などを効率的に行い、データベース操作をスムーズにするSkill。

📜 元の英語説明(参考)

MongoDB with Mongoose ODM - schemas, models, queries, aggregation, indexes, TypeScript typing, connection management

🇯🇵 日本人クリエイター向け解説

一言でいうと

Mongooseを使ってMongoDBのスキーマ定義、モデル作成、クエリ実行、集計、インデックス設定、TypeScript型付け、接続管理などを効率的に行い、データベース操作をスムーズにするSkill。

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o api-database-mongodb.zip https://jpskill.com/download/10234.zip && unzip -o api-database-mongodb.zip && rm api-database-mongodb.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/10234.zip -OutFile "$d\api-database-mongodb.zip"; Expand-Archive "$d\api-database-mongodb.zip" -DestinationPath $d -Force; ri "$d\api-database-mongodb.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して api-database-mongodb.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → api-database-mongodb フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

MongoDB / Mongoose のパターン

クイックガイド: MongoDB のための ODM として Mongoose を使用します。自動的な TypeScript 推論でスキーマを定義し、読み取り専用クエリには lean() を使用し、共同でアクセスされるデータには参照よりも埋め込みを優先し、集約パイプラインの早い段階で $match を配置し、クエリパターンに一致するように常にインデックスを定義します。


<critical_requirements>

重要: この Skill を使用する前に

すべてのコードは CLAUDE.md のプロジェクト規約に従う必要があります (kebab-case、名前付きエクスポート、インポート順序、import type、名前付き定数)

(Mongoose ミドルウェア (pre/post フック) は、model() を呼び出す前に定義する必要があります -- モデルコンパイル後に登録されたフックは、警告なしに無視されます)

(トランザクション内のすべての操作に { session } を渡す必要があります -- セッションがないと、操作はトランザクションの外部で実行されます)

(API レスポンスに結果を直接送信する読み取り専用クエリには、.lean() を使用する必要があります -- lean をスキップすると、ハイドレーションのオーバーヘッドで 3 倍のメモリが無駄になります)

(接続文字列では localhost の代わりに 127.0.0.1 を使用する必要があります -- Node.js 18+ は IPv6 を優先し、localhost は接続タイムアウトを引き起こす可能性があります)

( findOneAndUpdate / updateOne を使用して save ミドルウェアが発火することを期待してはいけません -- save()create() のみがドキュメントミドルウェアをトリガーします)

</critical_requirements>


自動検出: MongoDB, Mongoose, mongoose.connect, Schema, model, ObjectId, populate, aggregate, $match, $group, $lookup, lean, HydratedDocument, InferSchemaType, MongoClient, Atlas

いつ使うか:

  • Mongoose を使用した MongoDB スキーマとモデルの定義
  • CRUD 操作と複雑なクエリの構築
  • 分析とレポートのための集約パイプラインの設計
  • クエリパフォーマンスのためのインデックスの管理
  • MongoDB Atlas またはローカルインスタンスへの接続
  • ドキュメントの関係のモデリング (埋め込み vs 参照)

カバーされる主要なパターン:

  • 接続設定 (Atlas URI、プーリング、エラー処理)
  • スキーマ定義 (型、検証、デフォルト、列挙型)
  • TypeScript を使用したモデル (自動推論、メソッド、静的メソッド、仮想プロパティ)
  • CRUD 操作 (作成、検索、更新、削除、lean)
  • クエリの構築 (フィルター、射影、ソート、制限、populate)

いつ使わないか:

  • 複雑な結合と外部キー制約を持つ高度なリレーショナルデータ (リレーショナルデータベースを使用)
  • 主要なパターンとして、多くのコレクションにわたる強力な ACID 保証 (リレーショナルデータベースを使用)
  • 単純なキーと値のストレージ (専用のキーと値のストアを使用)
  • リレーショナル制約が重要な固定スキーマ
  • 大規模な時系列データ (専用の時系列データベースを使用)

詳細なリソース:

  • 意思決定フレームワークとアンチパターンについては、reference.md を参照してください。

コアパターン:

  • examples/core.md - 接続、スキーマ定義、モデル作成、TypeScript 型付け

クエリパターン:

  • examples/queries.md - 複雑なクエリ、populate、lean、カーソル、ページネーション

集約:

高度なパターン:

  • examples/patterns.md - スキーマ設計 (埋め込み vs 参照)、トランザクション、ミドルウェアフック、仮想プロパティ

インデックス:

  • examples/indexes.md - インデックス型、複合インデックス、テキスト検索、地理空間、TTL、パフォーマンス

<philosophy>

哲学

MongoDB はドキュメントデータベースです。Mongoose はその上にスキーマベースのモデリングを提供します。コアとなる原則: 一緒にアクセスされるデータは一緒に保存されるべきです。

コアとなる原則:

  1. スキーマファースト設計 -- モデルの前にスキーマを定義します。スキーマは、アプリケーション層で構造、検証、およびデフォルトを強制します。
  2. デフォルトで埋め込む -- 共同でアクセスされるデータは、同じドキュメントに属します。データが多くのドキュメント間で共有されているか、無制限に増加するか、または頻繁に個別に更新される場合にのみ参照します。
  3. 読み取りには lean を使用 -- 読み取り専用クエリには .lean() を使用します。完全な Mongoose ドキュメントの代わりに、プレーンなオブジェクト (メモリが 3 分の 1) を返します。
  4. クエリにインデックスを付ける -- すべてのクエリパターンには、サポートするインデックスが必要です。複合インデックスは、Equality-Sort-Range (ESR) ルールに従います。
  5. アプリケーションロジックよりも集約 -- アプリケーションコードで処理する代わりに、集約パイプラインを使用してデータ変換をデータベースにプッシュします。
  6. TypeScript 推論 -- Mongoose にスキーマ定義から型を推論させます。メソッド/静的メソッド/仮想プロパティが必要な場合を除き、インターフェースを手動で複製することは避けてください。

MongoDB / Mongoose を使用するタイミング:

  • ドキュメント指向のデータ (ユーザープロファイル、製品カタログ、コンテンツ)
  • 時間の経過とともに進化する柔軟なスキーマ
  • 階層型またはネストされたデータ構造
  • 埋め込みによる高い読み取りスループット
  • 地理空間クエリと全文検索

</philosophy>


<patterns>

コアパターン

パターン 1: 接続設定

起動時に、プール/タイムアウト設定の名前付き定数と、認証情報の環境変数を使用して、単一の接続を確立します。接続イベントと正常なシャットダウンを含む完全な例については、examples/core.md を参照してください。

const connection = await mongoose.connect(process.env.MONGODB_URI!, {
  maxPoolSize: POOL_SIZE_MAX,
  minPoolSize: POOL_SIZE_MIN,
  serverSelectionTimeoutMS: SERVER_SELECTION_TIMEOUT_MS,
  socketTimeoutMS: SOCKET_TIMEOUT_MS,
  retryWrites: true,
  retryReads: true,
});

パターン 2: TypeScript を使用したスキーマ定義

Mongoose にスキーマ定義から型を推論させます。メソッド、静的メソッド、または仮想プロパティを追加する場合にのみ、明示的なインターフェースを使用します。HydratedDocumentInferSchemaType、およびジェネリックパラメータを使用した完全な型付けの例については、examples/core.md を参照してください。


// 推奨: 自動型推論
const userSchema = new Schema(
  {
    name: { type: String, required: true, trim: true },
    email: { type: String, required: true, unique: true, lowercase: true },
    role: {
      type: String,
      enum: ["admin", "user", "moderator"] as const

(原文はここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

MongoDB / Mongoose Patterns

Quick Guide: Use Mongoose as the ODM for MongoDB. Define schemas with automatic TypeScript inference, use lean() for read-only queries, prefer embedding over referencing for co-accessed data, place $match early in aggregation pipelines, and always define indexes to match your query patterns.


<critical_requirements>

CRITICAL: Before Using This Skill

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

(You MUST define Mongoose middleware (pre/post hooks) BEFORE calling model() -- hooks registered after model compilation are silently ignored)

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

(You MUST use .lean() for read-only queries that send results directly to 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 can cause connection timeouts)

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

</critical_requirements>


Auto-detection: MongoDB, Mongoose, mongoose.connect, Schema, model, ObjectId, populate, aggregate, $match, $group, $lookup, lean, HydratedDocument, InferSchemaType, MongoClient, Atlas

When to use:

  • Defining MongoDB schemas and models with Mongoose
  • Building CRUD operations and complex queries
  • Designing aggregation pipelines for analytics and reporting
  • Managing indexes for query performance
  • Connecting to MongoDB Atlas or local instances
  • Modeling document relationships (embedding vs referencing)

Key patterns covered:

  • Connection setup (Atlas URI, pooling, error handling)
  • Schema definition (types, validation, defaults, enums)
  • Models with TypeScript (automatic inference, methods, statics, virtuals)
  • CRUD operations (create, find, update, delete, lean)
  • Query building (filters, projection, sort, limit, populate)

When NOT to use:

  • Highly relational data with complex joins and foreign key constraints (use a relational database)
  • Strong ACID guarantees across many collections as a primary pattern (use a relational database)
  • Simple key-value storage (use a dedicated key-value store)
  • Fixed schemas where relational constraints are critical
  • Time-series data at scale (use a dedicated time-series database)

Detailed Resources:

  • For decision frameworks and anti-patterns, see reference.md

Core Patterns:

  • examples/core.md - Connection, schema definition, model creation, TypeScript typing

Query Patterns:

Aggregation:

Advanced Patterns:

  • examples/patterns.md - Schema design (embedding vs referencing), transactions, middleware hooks, virtuals

Indexing:

  • examples/indexes.md - Index types, compound indexes, text search, geospatial, TTL, performance

<philosophy>

Philosophy

MongoDB is a document database. Mongoose provides schema-based modeling on top of it. The core principle: data that is accessed together should be stored together.

Core principles:

  1. Schema-first design -- Define schemas before models. Schemas enforce structure, validation, and defaults at the application layer.
  2. Embed by default -- Co-accessed data belongs in the same document. Only reference when data is shared across many documents, grows unbounded, or is frequently updated independently.
  3. Lean for reads -- Use .lean() for read-only queries. It returns plain objects (3x less memory) instead of full Mongoose documents.
  4. Index your queries -- Every query pattern needs a supporting index. Compound indexes follow the Equality-Sort-Range (ESR) rule.
  5. Aggregation over application logic -- Push data transformation to the database with aggregation pipelines instead of processing in application code.
  6. TypeScript inference -- Let Mongoose infer types from schema definitions. Avoid manually duplicating interfaces unless you need methods/statics/virtuals.

When to use MongoDB / Mongoose:

  • Document-oriented data (user profiles, product catalogs, content)
  • Flexible schemas that evolve over time
  • Hierarchical or nested data structures
  • High read throughput with embedding
  • Geospatial queries and full-text search

</philosophy>


<patterns>

Core Patterns

Pattern 1: Connection Setup

Establish a single connection at startup with named constants for pool/timeout config and environment variables for credentials. See examples/core.md for full examples including connection events and graceful shutdown.

const connection = await mongoose.connect(process.env.MONGODB_URI!, {
  maxPoolSize: POOL_SIZE_MAX,
  minPoolSize: POOL_SIZE_MIN,
  serverSelectionTimeoutMS: SERVER_SELECTION_TIMEOUT_MS,
  socketTimeoutMS: SOCKET_TIMEOUT_MS,
  retryWrites: true,
  retryReads: true,
});

Pattern 2: Schema Definition with TypeScript

Let Mongoose infer types from the schema definition. Use explicit interfaces only when adding methods, statics, or virtuals. See examples/core.md for full typing examples with HydratedDocument, InferSchemaType, and generic parameters.

// Preferred: automatic type inference
const userSchema = new Schema(
  {
    name: { type: String, required: true, trim: true },
    email: { type: String, required: true, unique: true, lowercase: true },
    role: {
      type: String,
      enum: ["admin", "user", "moderator"] as const,
      default: "user",
    },
  },
  { timestamps: true },
);
const User = model("User", userSchema);
// For methods/statics/virtuals: explicit interfaces with Schema generics
const userSchema = new Schema<IUser, UserModel, IUserMethods, {}, IUserVirtuals>({ ... });

Pattern 3: CRUD Operations

Use .lean() for read-only queries, save() when middleware must fire, findByIdAndUpdate with { runValidators: true } for direct updates. See examples/core.md for full CRUD examples.

const user = await User.findById(id).lean(); // read-only, 3x less memory
await User.insertMany(users, { ordered: false }); // bulk insert
await User.findByIdAndUpdate(id, update, { new: true, runValidators: true }); // direct update

Pattern 4: Query Building

Use comparison/logical operators for filters, .populate() with field selection and limits. See examples/queries.md for dynamic query builders, cursor-based pagination, and populate patterns.

const post = await Post.findById(id)
  .populate("author", "name email")
  .populate({
    path: "comments",
    options: { sort: { createdAt: -1 }, limit: 10 },
  })
  .lean();

Pattern 5: Schema Validation

Add custom error messages, regex validation, and array-level validators. See examples/core.md for complete validation examples.

price: {
  type: Number,
  required: true,
  min: [0, "Price cannot be negative"],
  validate: { validator: (v: number) => Number.isFinite(v), message: "Price must be finite" },
},
sku: {
  type: String,
  required: true,
  unique: true,
  match: [/^[A-Z]{2}-\d{6}$/, "SKU must match format XX-000000"],
},

</patterns>


<red_flags>

RED FLAGS

High Priority Issues:

  • Mutating a document fetched with .lean() and expecting .save() to work -- lean returns plain objects without Mongoose methods
  • Registering middleware after model() call -- hooks are silently ignored
  • Running operations in parallel inside a transaction (Promise.all()) -- MongoDB does not support parallel operations within a single transaction
  • Using localhost in connection strings on Node.js 18+ -- IPv6 preference causes connection timeouts, use 127.0.0.1
  • Missing { session } on any operation inside a transaction -- that operation runs outside the transaction

Medium Priority Issues:

  • Using findOneAndUpdate / updateOne and expecting pre('save') hooks to fire -- only save() and create() trigger document middleware
  • Unbounded .populate() without limit or field selection -- can return thousands of documents per query
  • Not calling runValidators: true on findOneAndUpdate -- schema validation is skipped by default on updates
  • Creating indexes in production code instead of migration scripts -- index builds lock the collection
  • Using $where or JavaScript expressions in queries -- disables indexes and enables injection

Common Mistakes:

  • Forgetting { new: true } on findOneAndUpdate -- returns the old document by default
  • Using Schema.Types.ObjectId in TypeScript interfaces instead of Types.ObjectId -- Schema.Types.ObjectId is for schema definitions, Types.ObjectId is for interfaces
  • Not handling duplicate key errors (code 11000) from unique indexes
  • Calling .lean() on write operations -- lean is for reads only
  • Checking doc.isNew in post('save') hooks -- always false after save, use this.$locals.wasNew set in a pre('save') hook

Gotchas & Edge Cases:

  • MongoDB has a 16 MB document size limit -- deeply embedded arrays can hit this
  • Mongoose buffers operations before connection is established -- queries queue silently if connection fails
  • deleteOne / deleteMany do not trigger pre('remove') middleware -- use findOneAndDelete or document .deleteOne() if you need middleware
  • Virtual properties are excluded from toJSON() / toObject() by default -- set { toJSON: { virtuals: true } } in schema options
  • remove() was completely removed in Mongoose 7+ -- use deleteOne() or deleteMany() instead
  • Mongoose 9 dropped callback-based next() in pre hooks -- use async/await instead
  • Mongoose 9 renamed FilterQuery to QueryFilter -- update TypeScript imports if upgrading
  • Mongoose 9 requires updatePipeline: true for pipeline-style updates -- they throw by default
  • Mongoose 9 removed the background index option -- MongoDB 4.2+ builds all indexes in the background by default

</red_flags>


<critical_reminders>

CRITICAL REMINDERS

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

(You MUST define Mongoose middleware (pre/post hooks) BEFORE calling model() -- hooks registered after model compilation are silently ignored)

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

(You MUST use .lean() for read-only queries that send results directly to 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 can cause connection timeouts)

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

Failure to follow these rules will cause silent data corruption, middleware bypass, or transaction isolation failures.

</critical_reminders>