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本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
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
$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. 下の青いボタンを押して
mongoose.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
mongooseフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
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
ベストプラクティス
- スキーマバリデーション — 厳密なスキーマを定義します。
required、enum、match、min/maxバリデーターを使用します。 - Lean クエリ — 読み取り専用クエリには
.lean()を使用します。プレーンオブジェクトを返し、Mongoose ドキュメントより 5 倍高速です。 - インデックス — クエリ/ソートするフィールドにインデックスを追加します。
explain()を使用してクエリプランを検証します。 - ポピュレーション —
populate()の使用は控えめにします。複雑な結合には、集約$lookupを優先します。 - ミドルウェア — ハッシュ化、バリデーションには
pre('save')を使用します。通知、ロギングにはpost('save')を使用します。 - タイムスタンプ —
timestamps: trueを有効にします。createdAtとupdatedAtを自動的に管理します。 - トランザクション — 複数ドキュメント操作にはセッションを使用します。レプリカセットまたは MongoDB Atlas が必要です。
- TypeScript —
Documentを拡張するインターフェースを定義します。完全な型安全性のために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
- Schema validation — Define strict schemas; use
required,enum,match,min/maxvalidators - Lean queries — Use
.lean()for read-only queries; returns plain objects, 5x faster than Mongoose documents - Indexes — Add indexes for fields you query/sort by; use
explain()to verify query plans - Population — Use
populate()sparingly; for complex joins, prefer aggregation$lookup - Middleware — Use
pre('save')for hashing, validation;post('save')for notifications, logging - Timestamps — Enable
timestamps: true; auto-managescreatedAtandupdatedAt - Transactions — Use sessions for multi-document operations; requires replica set or MongoDB Atlas
- TypeScript — Define interfaces extending
Document; use generics withSchema<IUser>for full type safety