本文へ移動
cccskills
無料GitHub で公開

mongodb-mongoose

MongoDB with Mongoose — schemas, models, aggregation pipelines, migrations, and Atlas connections. Use when designing collections, writing queries, or integrating MongoDB into Node.js/Next.js apps.

インストール方法を見る

含まれるファイル(3)

  • SKILL.md11.9 KB
  • CHANGELOG.md4.5 KB
  • LICENSE.txt1.0 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Mongodb Mongoose

Optimized for current MongoDB server releases, Mongoose 8.x+, Node.js 22+, and TypeScript 5.5+.

Comprehensive guidance for MongoDB database design, Mongoose ODM patterns, and Atlas integration for Node.js/Next.js applications.

  • Leverage native parallel subagent dispatch and 200k+ context windows where available.

When to Use This Skill

Use symptom -> action triggers: when one matches, apply this skill and verify with the protocol below.

  • Designing MongoDB schemas and data models
  • Building Mongoose models with validation and middleware
  • Implementing the repository pattern for data access
  • Writing aggregation pipelines for complex queries
  • Managing MongoDB Atlas connections and configuration
  • Integrating MongoDB with Next.js API routes
  • Database migration strategies

Anti-Patterns

  • Modeling documents like normalized tables by default: MongoDB performance depends on query-driven shape, not relational purity.
  • Returning full hydrated documents for every request: Over-fetching and hydration overhead accumulate quickly in API paths.
  • Adding middleware without write-path tests: Hooks can silently change create, update, and migration behavior.

Verification Protocol

Before claiming "skill applied successfully":

  1. Pass/fail: The Mongodb Mongoose implementation names the target runtime, framework version, and affected files.
  2. Pass/fail: Build, lint, test, or equivalent local validation is run for the changed surface.
  3. Pass/fail: Edge cases for errors, dependency drift, and environment differences are addressed or explicitly out of scope.
  4. Pressure-test scenario: Apply the workflow to a change that passes happy-path tests but fails one boundary condition.
  5. Success metric: Zero untested success claims; every implementation claim maps to a command or artifact.

Before and After Example

// Before
const recipes = await Recipe.find({ author: userId }).populate('author');

// After
const recipes = await Recipe.find({ author: userId, isPublished: true })
  .select({ title: 1, slug: 1, createdAt: 1 })
  .sort({ createdAt: -1 })
  .lean();

Narrows the query shape, avoids unnecessary hydration, and aligns the result with the view model actually needed.

Schema Design

Data Modeling Principles

  • Embed when data is accessed together and has a 1:few relationship
  • Reference when data is accessed independently or has a 1:many/many:many relationship
  • Design schemas around query patterns, not normalized relational models
  • Use denormalization strategically for read performance

Mongoose Model Pattern

import mongoose from 'mongoose';

const recipeSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, 'Title is required'],
    trim: true,
    maxlength: [200, 'Title cannot exceed 200 characters'],
    index: true,
  },
  slug: {
    type: String,
    unique: true,
    lowercase: true,
  },
  ingredients: [{
    name: { type: String, required: true },
    amount: { type: Number, required: true },
    unit: { type: String, enum: ['g', 'kg', 'ml', 'l', 'cup', 'tbsp', 'tsp', 'piece'] },
  }],
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
    index: true,
  },
  tags: [{ type: String, lowercase: true, trim: true }],
  isPublished: { type: Boolean, default: false },
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true },
});

// Indexes for common queries
recipeSchema.index({ title: 'text', tags: 'text' });
recipeSchema.index({ author: 1, createdAt: -1 });

// Virtual fields
recipeSchema.virtual('ingredientCount').get(function() {
  return this.ingredients.length;
});

// Pre-save middleware
recipeSchema.pre('save', function(next) {
  if (this.isModified('title')) {
    this.slug = this.title.toLowerCase().replace(/[^a-z0-9]+/g, '-');
  }
  next();
});

export const Recipe = mongoose.models.Recipe || mongoose.model('Recipe', recipeSchema);

Schema Best Practices

  • Always define required, type, and validation rules
  • Use timestamps: true for automatic createdAt/updatedAt
  • Add indexes for frequently queried fields
  • Use enum for fields with fixed values
  • Define virtuals for computed properties
  • Use middleware (pre/post hooks) for side effects

Repository Pattern

class RecipeRepository {
  async findAll(filter = {}, options = {}) {
    const { page = 1, limit = 20, sort = '-createdAt', populate = '' } = options;
    const skip = (page - 1) * limit;

    const [recipes, total] = await Promise.all([
      Recipe.find(filter)
        .sort(sort)
        .skip(skip)
        .limit(limit)
        .populate(populate)
        .lean(),
      Recipe.countDocuments(filter),
    ]);

    return {
      data: recipes,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit),
      },
    };
  }

  async findById(id) {
    return Recipe.findById(id).populate('author', 'name avatar').lean();
  }

  async create(data) {
    const recipe = new Recipe(data);
    return recipe.save();
  }

  async update(id, data) {
    return Recipe.findByIdAndUpdate(id, data, {
      new: true,
      runValidators: true,
    });
  }

  async delete(id) {
    return Recipe.findByIdAndDelete(id);
  }

  async search(query, options = {}) {
    return this.findAll(
      { $text: { $search: query } },
      { ...options, sort: { score: { $meta: 'textScore' } } }
    );
  }
}

export const recipeRepository = new RecipeRepository();

Aggregation Pipelines

Common Patterns

// Group recipes by tag with counts
const tagStats = await Recipe.aggregate([
  { $match: { isPublished: true } },
  { $unwind: '$tags' },
  { $group: { _id: '$tags', count: { $sum: 1 } } },
  { $sort: { count: -1 } },
  { $limit: 20 },
]);

// Author statistics with lookup
const authorStats = await Recipe.aggregate([
  { $group: {
    _id: '$author',
    recipeCount: { $sum: 1 },
    avgRating: { $avg: '$rating' },
  }},
  { $lookup: {
    from: 'users',
    localField: '_id',
    foreignField: '_id',
    as: 'authorInfo',
  }},
  { $unwind: '$authorInfo' },
  { $project: {
    name: '$authorInfo.name',
    recipeCount: 1,
    avgRating: { $round: ['$avgRating', 1] },
  }},
  { $sort: { recipeCount: -1 } },
]);

// Date-based analytics
const monthlyRecipes = await Recipe.aggregate([
  { $match: { createdAt: { $gte: new Date('2024-01-01') } } },
  { $group: {
    _id: { $dateToString: { format: '%Y-%m', date: '$createdAt' } },
    count: { $sum: 1 },
  }},
  { $sort: { _id: 1 } },
]);

Atlas Connection

Connection Setup (Next.js)

import mongoose from 'mongoose';

const MONGODB_URI = process.env.MONGODB_URI;

if (!MONGODB_URI) {
  throw new Error('MONGODB_URI environment variable is not defined');
}

let cached = global.mongoose;
if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}

export async function connectDB() {
  if (cached.conn) return cached.conn;

  if (!cached.promise) {
    cached.promise = mongoose.connect(MONGODB_URI, {
      bufferCommands: false,
    });
  }

  cached.conn = await cached.promise;
  return cached.conn;
}

Connection Best Practices

  • Cache connection in development to prevent multiple connections
  • Use bufferCommands: false for explicit error handling
  • Set connection pool size via maxPoolSize for production
  • Use Atlas connection string with retryWrites=true&w=majority

Migration Strategies

Document Versioning

const userSchema = new mongoose.Schema({
  schemaVersion: { type: Number, default: 2 },
  // ... fields
});

userSchema.pre('save', function(next) {
  if (this.schemaVersion < 2) {
    // Migrate old fields to new format
    this.schemaVersion = 2;
  }
  next();
});

Batch Migration Script

async function migrateUsers() {
  const batchSize = 100;
  let processed = 0;
  let batch;

  do {
    batch = await User.find({ schemaVersion: { $lt: 2 } }).limit(batchSize);
    for (const user of batch) {
      user.schemaVersion = 2;
      await user.save();
      processed++;
    }
    console.log(`Migrated ${processed} users`);
  } while (batch.length === batchSize);
}

Performance Tips

  • Use .lean() for read-only queries (returns plain objects, 5-10x faster)
  • Use .select() to return only needed fields
  • Create compound indexes matching your query patterns
  • Use $project early in aggregation to reduce working set
  • Avoid $lookup in high-frequency queries; denormalize instead
  • Use explain() to analyze query performance

Troubleshooting

IssueSolution
Slow queriesAdd indexes, use .lean(), check with explain()
Connection timeoutsCheck Atlas network access, increase pool size
Validation errorsReview schema constraints, check middleware order
Duplicate key errorsEnsure unique indexes, handle with try/catch
Memory issuesUse cursors for large datasets, limit batch sizes

Common Pitfalls

  • Modeling data like a normalized relational schema by default: MongoDB performance depends on query-driven document shape, not tables-first design.
  • Returning full hydrated documents everywhere: Hydration and over-fetching add cost when a lean projection would do.
  • Adding middleware without explicit write-path tests: Hooks can silently change behavior in create, update, and migration flows.

References & Resources

Documentation

Scripts

  • Seed Database — Zero-dependency MongoDB seeding script with sample recipe data

Examples

  • Recipe API Example — Complete Mongoose + Next.js Recipe CRUD API with models, routes, and validation

<!-- MCP:START --> <!-- PORTABILITY:START -->

Cross-Client Portability

This skill is written to stay usable across GitHub Copilot, Claude Code, and Codex.

  • GitHub Copilot: keep the folder in a Copilot-visible skill path or wrap the workflow in project instructions when folder discovery is unavailable.
  • Claude Code: keep the folder in a local skills directory or a compatible plugin source.
  • Codex: install or sync the folder into $CODEX_HOME/skills/mongodb-mongoose and restart Codex after major changes.
<!-- PORTABILITY:END -->

MCP Availability And Fallback

Preferred MCP Server: MongoDB MCP

  • Fallback prompt: "Use the Mongodb Mongoose skill without MCP. Rely on the local SKILL.md, bundled references or scripts, and manual verification. Show the exact commands, evidence, and final checks you used before concluding."
  • Use mongosh, MongoDB Atlas UI, local schema files, and Mongoose model inspection when the MCP server is unavailable.
  • Validate indexes, queries, and aggregation pipelines against a local or staging database before finalizing changes.
<!-- MCP:END -->

Related Skills

  • javascript-development: Use it when the workflow also needs modern JavaScript and TypeScript application code.
  • nextjs-development: Use it when the workflow also needs Next.js App Router and server-first React patterns.
  • sql-development: Use it when the workflow also needs SQL query, schema, and performance tuning work.
  • code-quality: Use it when the workflow also needs two-stage review (spec compliance first, then code quality), maintainability, and refactoring guidance.

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

AI-powered adeno-associated virus (AAV) vector design for gene therapy including capsid engineering, promoter selection, and tropism optimization.

日本語の概要は準備中です。原文の説明を表示しています。

bg-szy/TOP-SKILLS62026年9月8日 更新

Improve the clarity and voice of AI-assisted academic writing (papers, theses, rebuttals) and

日本語の概要は準備中です。原文の説明を表示しています。

bg-szy/TOP-SKILLS62026年9月8日 更新

12-agent academic paper writing pipeline. 11 modes (full/plan/outline/revision/revision-coach/abstract/lit-review/format-convert/citation-check/disclosure/rebuttal-audit). 6 paper types, 5 citation formats, bilingual abstracts, LaTeX/DOCX-via-Pandoc/PDF output. Style Calibration + Writing Quality Check + Anti-Patterns with IRON RULE markers. Triggers: write paper, academic paper, guide my paper, parse reviews, audit my rebuttal, check my response draft, AI disclosure, 寫論文, 學術論文, 引導我寫論文, 審查意見, 評估回覆, 논문 작성, 초록 작성, 논문 수정, 논문 계획을 도와줘, 심사 의견 반영, 답변서 점검, AI 사용 고지.

日本語の概要は準備中です。原文の説明を表示しています。

bg-szy/TOP-SKILLS62026年9月8日 更新

Systematic writing framework for philosophy and interdisciplinary academic papers from optimized outline to submission-ready manuscript. Use when users want to: (1) write a paper from a detailed outline, (2) ensure quality control during writing, (3) maintain consistency across chapters, (4) prepare a submission-ready manuscript, or (5) systematically execute a planned paper. Triggered by phrases like 'write the paper from this outline,' 'compose the full manuscript,' 'execute the outline,' or when users have completed strategic planning (academic-paper-strategist skill) and are ready to write. Takes optimized outline as input; outputs complete manuscript with iterative quality checks.

日本語の概要は準備中です。原文の説明を表示しています。

bg-szy/TOP-SKILLS62026年9月8日 更新

Multi-perspective academic paper review with dynamic reviewer personas. Runs a 5-seat, role-separated review panel (Journal-Fit Reviewer + 3 peer-review roles + Devil's Advocate) with field-specific expertise; role separation is not a claim of independent error processes. Supports full review, re-review (verification), quick assessment, methodology focus, Socratic guided, and calibration modes. Triggers on: review paper, peer review, manuscript review, referee report, review my paper, critique paper, simulate review, editorial review, calibrate reviewer, reviewer calibration, measure reviewer accuracy, 審查論文, 論文審查, 模擬審查, 同儕審查, 幫我審這篇, 以審查人角度評估, 審查者校準, 논문 심사, 동료 심사, 모의 심사, 심사자 관점에서 평가, 심사자 보정.

日本語の概要は準備中です。原文の説明を表示しています。

bg-szy/TOP-SKILLS62026年9月8日 更新

Systematic strategic planning framework for philosophy and interdisciplinary academic papers targeting preprint platforms (PhilArchive, arXiv, PhilSci-Archive). Use when users want to: (1) plan a paper on a specific topic, (2) identify research gaps and assess originality, (3) develop optimized paper outlines, (4) prepare for preprint submission, or (5) understand platform requirements and writing standards. Triggered by phrases like 'plan a paper on,' 'help me design a paper about,' 'identify research gaps in,' 'is this idea original,' or when users need structured research planning. The skill guides through three phases: Platform Analysis (identifying target venue and studying sample papers), Theoretical Framework (AI-driven literature search and gap identification), and Outline Optimization (structured design with reviewer-perspective self-assessment). Each phase includes quality evaluation standards and validation checkpoints.

日本語の概要は準備中です。原文の説明を表示しています。

bg-szy/TOP-SKILLS62026年9月8日 更新

bg-szy のスキルをすべて見る

このスキルの問題を報告する