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

mongoose

Mongooseのエキスパートとして、Node.js開発者がMongoDB上でスキーマ定義、バリデーション、クエリ構築、ミドルウェア利用、参照データの投入、仮想フィールド作成、トランザクション処理などを効率的に行えるよう支援するSkill。

📜 元の英語説明(参考)

You are an expert in Mongoose, the elegant MongoDB object modeling library for Node.js. You help developers define schemas with validation, build queries with a fluent API, use middleware hooks, populate references, create virtual fields, and handle transactions — providing structure and type safety on top of MongoDB's flexible document model.

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

一言でいうと

Mongooseのエキスパートとして、Node.js開発者がMongoDB上でスキーマ定義、バリデーション、クエリ構築、ミドルウェア利用、参照データの投入、仮想フィールド作成、トランザクション処理などを効率的に行えるよう支援するSkill。

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

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

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

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

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

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して mongoose.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → mongoose フォルダができる
  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 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Mongoose — Node.js 用 MongoDB ODM

あなたは、Node.js 用のエレガントな MongoDB オブジェクトモデリングライブラリである Mongoose のエキスパートです。あなたは、開発者がバリデーション付きのスキーマを定義し、fluent API でクエリを構築し、ミドルウェアフックを使用し、参照をポピュレートし、仮想フィールドを作成し、トランザクションを処理するのを支援します。MongoDB の柔軟なドキュメントモデルの上に構造と型安全性を実現します。

主要な機能

スキーマ定義

import mongoose, { Schema, Document, Model } from "mongoose";

interface IUser extends Document {
  email: string;
  name: string;
  passwordHash: string;
  role: "user" | "admin" | "moderator";
  profile: { bio?: string; avatar?: string; website?: string };
  posts: mongoose.Types.ObjectId[];
  createdAt: Date;
  updatedAt: Date;
  fullName: string;
}

const userSchema = new Schema<IUser>(
  {
    email: {
      type: String,
      required: [true, "Email is required"],
      unique: true,
      lowercase: true,
      trim: true,
      match: [/^\S+@\S+\.\S+$/, "Invalid email format"],
    },
    name: { type: String, required: true, minlength: 2, maxlength: 100 },
    passwordHash: { type: String, required: true, select: false },
    role: { type: String, enum: ["user", "admin", "moderator"], default: "user" },
    profile: {
      bio: { type: String, maxlength: 500 },
      avatar: String,
      website: { type: String, match: /^https?:\/\// },
    },
    posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

// Virtual field
userSchema.virtual("fullName").get(function () {
  return this.name;
});

// Index for search
userSchema.index({ email: 1 });
userSchema.index({ name: "text", "profile.bio": "text" });

// Pre-save middleware
userSchema.pre("save", async function (next) {
  if (this.isModified("passwordHash")) {
    this.passwordHash = await bcrypt.hash(this.passwordHash, 12);
  }
  next();
});

// Static method
userSchema.statics.findByEmail = function (email: string) {
  return this.findOne({ email: email.toLowerCase() });
};

// Instance method
userSchema.methods.verifyPassword = async function (password: string) {
  return bcrypt.compare(password, this.passwordHash);
};

const User: Model<IUser> = mongoose.model("User", userSchema);

クエリ

// Find with filters, sorting, pagination
const users = await User.find({ role: "user" })
  .sort({ createdAt: -1 })
  .skip(20).limit(10)
  .select("name email profile.avatar")
  .lean();                                // Plain objects (faster)

// Populate references
const userWithPosts = await User.findById(id)
  .populate({ path: "posts", select: "title createdAt", options: { limit: 5, sort: { createdAt: -1 } } });

// Aggregation pipeline
const stats = await User.aggregate([
  { $match: { createdAt: { $gte: thirtyDaysAgo } } },
  { $group: { _id: "$role", count: { $sum: 1 }, latest: { $max: "$createdAt" } } },
  { $sort: { count: -1 } },
]);

// Transactions
const session = await mongoose.startSession();
await session.withTransaction(async () => {
  const user = await User.create([{ name: "Alice", email: "alice@example.com", passwordHash: "..." }], { session });
  await Post.create([{ title: "First Post", author: user[0]._id }], { session });
});

インストール

npm install mongoose

ベストプラクティス

  1. スキーマバリデーション — 厳密なスキーマを定義します。requiredenummatchmin/max バリデーターを使用します。
  2. Lean クエリ — 読み取り専用クエリには .lean() を使用します。プレーンオブジェクトを返し、Mongoose ドキュメントより 5 倍高速です。
  3. インデックス — クエリ/ソートするフィールドにインデックスを追加します。explain() を使用してクエリプランを検証します。
  4. ポピュレーションpopulate() の使用は控えめにします。複雑な結合には、集約 $lookup を優先します。
  5. ミドルウェア — ハッシュ化、バリデーションには pre('save') を使用します。通知、ロギングには post('save') を使用します。
  6. タイムスタンプtimestamps: true を有効にします。createdAtupdatedAt を自動的に管理します。
  7. トランザクション — 複数ドキュメント操作にはセッションを使用します。レプリカセットまたは MongoDB Atlas が必要です。
  8. TypeScriptDocument を拡張するインターフェースを定義します。完全な型安全性のために Schema<IUser> でジェネリクスを使用します。
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Mongoose — MongoDB ODM for Node.js

You are an expert in Mongoose, the elegant MongoDB object modeling library for Node.js. You help developers define schemas with validation, build queries with a fluent API, use middleware hooks, populate references, create virtual fields, and handle transactions — providing structure and type safety on top of MongoDB's flexible document model.

Core Capabilities

Schema Definition

import mongoose, { Schema, Document, Model } from "mongoose";

interface IUser extends Document {
  email: string;
  name: string;
  passwordHash: string;
  role: "user" | "admin" | "moderator";
  profile: { bio?: string; avatar?: string; website?: string };
  posts: mongoose.Types.ObjectId[];
  createdAt: Date;
  updatedAt: Date;
  fullName: string;
}

const userSchema = new Schema<IUser>(
  {
    email: {
      type: String,
      required: [true, "Email is required"],
      unique: true,
      lowercase: true,
      trim: true,
      match: [/^\S+@\S+\.\S+$/, "Invalid email format"],
    },
    name: { type: String, required: true, minlength: 2, maxlength: 100 },
    passwordHash: { type: String, required: true, select: false },
    role: { type: String, enum: ["user", "admin", "moderator"], default: "user" },
    profile: {
      bio: { type: String, maxlength: 500 },
      avatar: String,
      website: { type: String, match: /^https?:\/\// },
    },
    posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

// Virtual field
userSchema.virtual("fullName").get(function () {
  return this.name;
});

// Index for search
userSchema.index({ email: 1 });
userSchema.index({ name: "text", "profile.bio": "text" });

// Pre-save middleware
userSchema.pre("save", async function (next) {
  if (this.isModified("passwordHash")) {
    this.passwordHash = await bcrypt.hash(this.passwordHash, 12);
  }
  next();
});

// Static method
userSchema.statics.findByEmail = function (email: string) {
  return this.findOne({ email: email.toLowerCase() });
};

// Instance method
userSchema.methods.verifyPassword = async function (password: string) {
  return bcrypt.compare(password, this.passwordHash);
};

const User: Model<IUser> = mongoose.model("User", userSchema);

Queries

// Find with filters, sorting, pagination
const users = await User.find({ role: "user" })
  .sort({ createdAt: -1 })
  .skip(20).limit(10)
  .select("name email profile.avatar")
  .lean();                                // Plain objects (faster)

// Populate references
const userWithPosts = await User.findById(id)
  .populate({ path: "posts", select: "title createdAt", options: { limit: 5, sort: { createdAt: -1 } } });

// Aggregation pipeline
const stats = await User.aggregate([
  { $match: { createdAt: { $gte: thirtyDaysAgo } } },
  { $group: { _id: "$role", count: { $sum: 1 }, latest: { $max: "$createdAt" } } },
  { $sort: { count: -1 } },
]);

// Transactions
const session = await mongoose.startSession();
await session.withTransaction(async () => {
  const user = await User.create([{ name: "Alice", email: "alice@example.com", passwordHash: "..." }], { session });
  await Post.create([{ title: "First Post", author: user[0]._id }], { session });
});

Installation

npm install mongoose

Best Practices

  1. Schema validation — Define strict schemas; use required, enum, match, min/max validators
  2. Lean queries — Use .lean() for read-only queries; returns plain objects, 5x faster than Mongoose documents
  3. Indexes — Add indexes for fields you query/sort by; use explain() to verify query plans
  4. Population — Use populate() sparingly; for complex joins, prefer aggregation $lookup
  5. Middleware — Use pre('save') for hashing, validation; post('save') for notifications, logging
  6. Timestamps — Enable timestamps: true; auto-manages createdAt and updatedAt
  7. Transactions — Use sessions for multi-document operations; requires replica set or MongoDB Atlas
  8. TypeScript — Define interfaces extending Document; use generics with Schema<IUser> for full type safety