mongoose-mongodb について
mongoose-mongodb は、Mongoose を使って MongoDB を扱う Node.js 開発者向けの学習スキルです。接続やデータモデリングから CRUD、高度なデータベース設計まで扱います。
主な機能
- 01接続設定とエラー処理
- 02スキーマとモデルの定義
- 03CRUD 操作とクエリ
- 04関連付けと populate
- 05インデックス、ミドルウェア、仮想プロパティ
- 06集計とトランザクション
活用シーン
- 01Node.js アプリを MongoDB に接続
- 02アプリデータのモデリングと検証
- 03関連ドキュメントの検索
- 04一般的なデータベース操作の最適化
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ pluginagentmarketplace/ custom-plugin-nodejs --skill mongoose-mongodbインストール後、Claude Code で/mongoose-mongodbを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
assets/config.yamlreferences/GUIDE.mdscripts/helper.py詳細
Mongoose と MongoDB のスキル
エレガントなオブジェクトモデリングライブラリである Mongoose を使用して、Node.js での MongoDB データベース連携を習得します。
クイックスタート
4 つのステップで接続と CRUD を実行します。
- インストール -
npm install mongoose - 接続 -
mongoose.connect(uri) - スキーマの定義 - データモデルを作成します
- CRUD - 作成、読み取り、更新、削除
基本概念
接続の設定
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
mongoose.connection.on('connected', () => {
console.log('MongoDB connected');
});
スキーマとモデル
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Name is required'],
trim: true,
minlength: 3,
maxlength: 50
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
age: {
type: Number,
min: 18,
max: 120
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user'
}
}, {
timestamps: true // createdAt, updatedAt
});
const User = mongoose.model('User', userSchema);
CRUD 操作
// Create
const user = await User.create({
name: 'John Doe',
email: '[email protected]'
});
// Read
const users = await User.find({ age: { $gte: 18 } });
const user = await User.findById(id);
const user = await User.findOne({ email: '[email protected]' });
// Update
const updated = await User.findByIdAndUpdate(
id,
{ name: 'Jane Doe' },
{ new: true, runValidators: true }
);
// Delete
await User.findByIdAndDelete(id);
await User.deleteMany({ age: { $lt: 18 } });
リレーションシップと Populate
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
});
// Populate relationship
const post = await Post.findById(id).populate('author');
// post.author is now full user object
学習パス
初級(2~3 週間)
- ✅ MongoDB と Mongoose をインストールします
- ✅ スキーマとモデルを作成します
- ✅ CRUD 操作を行います
- ✅ 基本的なクエリを使用します
中級(4~5 週間)
- ✅ リレーションシップと Populate
- ✅ バリデーションとミドルウェア
- ✅ パフォーマンス向上のためのインデックス
- ✅ クエリ演算子
上級(6~8 週間)
- ✅ 集約パイプライン
- ✅ トランザクション
- ✅ スキーマ設計パターン
- ✅ パフォーマンスの最適化
高度な機能
インデックス
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ name: 1, age: -1 });
ミドルウェア(フック)
userSchema.pre('save', async function(next) {
if (this.isModified('password')) {
this.password = await bcrypt.hash(this.password, 10);
}
next();
});
仮想プロパティ
userSchema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});
集約パイプライン
const stats = await User.aggregate([
{ $match: { age: { $gte: 18 } } },
{ $group: {
_id: '$role',
count: { $sum: 1 },
avgAge: { $avg: '$age' }
}},
{ $sort: { count: -1 } }
]);
クエリ演算子
// Comparison
User.find({ age: { $gt: 18 } }) // Greater than
User.find({ age: { $gte: 18 } }) // Greater or equal
User.find({ age: { $lt: 65 } }) // Less than
User.find({ age: { $lte: 65 } }) // Less or equal
User.find({ age: { $ne: 30 } }) // Not equal
// Logical
User.find({ $and: [{ age: { $gte: 18 } }, { age: { $lte: 65 } }] })
User.find({ $or: [{ role: 'admin' }, { role: 'moderator' }] })
// Array
User.find({ tags: { $in: ['node', 'mongodb'] } })
User.find({ tags: { $nin: ['deprecated'] } })
// Regex
User.find({ email: /gmail\.com$/ })
ベストプラクティス
- ✅ 接続文字列には環境変数を使用します
- ✅ 頻繁にクエリされるフィールドにはインデックスを作成します
- ✅ 読み取り専用クエリには
lean()を使用します(パフォーマンスが向上します) - ✅ スキーマレベルでデータを検証します
- ✅ 複数ドキュメントにまたがる操作にはトランザクションを使用します
- ✅ 接続エラーを適切に処理します
- ✅ アプリのシャットダウン時に接続を閉じます
使用する場面
次のような場合は、Mongoose と MongoDB を使用します。
- Node.js アプリケーションを構築する場合
- 柔軟なスキーマ(ドキュメントベース)が必要な場合
- 大量のデータを扱う場合
- 迅速なプロトタイピングと反復を行う場合
- JSON に似たデータを扱う場合
関連スキル
- Express REST API(MongoDB に接続)
- 非同期プログラミング(非同期データベース操作)
- JWT 認証(ユーザーを保存)
- Jest テスト(データベース操作をテスト)
リソース
コメント
Markdown 対応