[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73AMFQFJYHFR5W6YE50CDZD":3,"skill-same:01M73AMFQFJYHFR5W6YE50CDZD":68},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":33,"commitSha":34,"skillDirectory":35,"forksCount":36,"repositoryHtmlUrl":37,"repositoryHomepageUrl":38,"ownerHtmlUrl":39,"ownerBlogUrl":40,"ownerDescription":41,"updatedAt":42,"install":43,"resources":56},"01M73AMFQFJYHFR5W6YE50CDZD","mongodb-mongoose",null,"MongoDB with Mongoose — schemas, models, aggregation pipelines, migrations, and Atlas connections. Use when designing collections, writing queries, or integrating MongoDB into Node.js\u002FNext.js apps.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fagent-skills\u002Fmongodb-mongoose\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fagent-skills\u002Fmongodb-mongoose\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: mongodb-mongoose\nversion: \"2.0\"\nlast_updated: 2026-09-08\ntags: [mongodb, mongoose, development, testing, quality]\ndescription: \"MongoDB with Mongoose — schemas, models, aggregation pipelines, migrations, and Atlas connections. Use when designing collections, writing queries, or integrating MongoDB into Node.js\u002FNext.js apps.\"\n---\n# Mongodb Mongoose\n\n> Optimized for current MongoDB server releases, Mongoose 8.x+, Node.js 22+, and TypeScript 5.5+.\n\nComprehensive guidance for MongoDB database design, Mongoose ODM patterns, and Atlas integration for Node.js\u002FNext.js applications.\n\n- Leverage native parallel subagent dispatch and 200k+ context windows where available.\n\n\n## When to Use This Skill\n\nUse symptom -> action triggers: when one matches, apply this skill and verify with the protocol below.\n\n- Designing MongoDB schemas and data models\n- Building Mongoose models with validation and middleware\n- Implementing the repository pattern for data access\n- Writing aggregation pipelines for complex queries\n- Managing MongoDB Atlas connections and configuration\n- Integrating MongoDB with Next.js API routes\n- Database migration strategies\n\n\n---\n\n\u003C!-- MCP:START -->\n\n\u003C!-- PORTABILITY:START -->\n## Cross-Client Portability\n\nThis skill is written to stay usable across GitHub Copilot, Claude Code, and Codex.\n\n- GitHub Copilot: keep the folder in a Copilot-visible skill path or wrap the\n  workflow in project instructions when folder discovery is unavailable.\n- Claude Code: keep the folder in a local skills directory or a compatible plugin source.\n- Codex: install or sync the folder into\n  `$CODEX_HOME\u002Fskills\u002Fmongodb-mongoose` and restart Codex after major changes.\n\n\u003C!-- PORTABILITY:END -->\n\n## MCP Availability And Fallback\n\nPreferred MCP Server: MongoDB MCP\n\n- Fallback prompt: \"Use the Mongodb Mongoose skill without MCP. Follow the documented local or manual fallback, show the selected tool surface, and report the verification evidence.\"\n- Use `mongosh`, MongoDB Atlas UI, local schema files, and Mongoose model inspection when the MCP server is unavailable.\n- Validate indexes, queries, and aggregation pipelines against a local or staging database before finalizing changes.\n- Do not claim an MCP operation was used when the active host does not expose it.\n\n\u003C!-- MCP:END -->\n\n## Anti-Patterns\n\n- Modeling documents like normalized tables by default: MongoDB performance depends on query-driven shape, not relational purity.\n- Returning full hydrated documents for every request: Over-fetching and hydration overhead accumulate quickly in API paths.\n- Adding middleware without write-path tests: Hooks can silently change create, update, and migration behavior.\n\n## Verification Protocol\n\nBefore claiming \"skill applied successfully\":\n\n1. Pass\u002Ffail: The Mongodb Mongoose implementation names the target runtime, framework version, and affected files.\n2. Pass\u002Ffail: Build, lint, test, or equivalent local validation is run for the changed surface.\n3. Pass\u002Ffail: Edge cases for errors, dependency drift, and environment differences are addressed or explicitly out of scope.\n4. Pressure-test scenario: Apply the workflow to a change that passes happy-path tests but fails one boundary condition.\n5. Success metric: Zero untested success claims; every implementation claim maps to a command or artifact.\n\n## Before and After Example\n\n```javascript\n\u002F\u002F Before\nconst recipes = await Recipe.find({ author: userId }).populate('author');\n\n\u002F\u002F After\nconst recipes = await Recipe.find({ author: userId, isPublished: true })\n  .select({ title: 1, slug: 1, createdAt: 1 })\n  .sort({ createdAt: -1 })\n  .lean();\n```\n\nNarrows the query shape, avoids unnecessary hydration, and aligns the result with the view model actually needed.\n\n## Schema Design\n\n### Data Modeling Principles\n- **Embed** when data is accessed together and has a 1:few relationship\n- **Reference** when data is accessed independently or has a 1:many\u002Fmany:many relationship\n- Design schemas around query patterns, not normalized relational models\n- Use denormalization strategically for read performance\n\n### Mongoose Model Pattern\n```javascript\nimport mongoose from 'mongoose';\n\nconst recipeSchema = new mongoose.Schema({\n  title: {\n    type: String,\n    required: [true, 'Title is required'],\n    trim: true,\n    maxlength: [200, 'Title cannot exceed 200 characters'],\n    index: true,\n  },\n  slug: {\n    type: String,\n    unique: true,\n    lowercase: true,\n  },\n  ingredients: [{\n    name: { type: String, required: true },\n    amount: { type: Number, required: true },\n    unit: { type: String, enum: ['g', 'kg', 'ml', 'l', 'cup', 'tbsp', 'tsp', 'piece'] },\n  }],\n  author: {\n    type: mongoose.Schema.Types.ObjectId,\n    ref: 'User',\n    required: true,\n    index: true,\n  },\n  tags: [{ type: String, lowercase: true, trim: true }],\n  isPublished: { type: Boolean, default: false },\n}, {\n  timestamps: true,\n  toJSON: { virtuals: true },\n  toObject: { virtuals: true },\n});\n\n\u002F\u002F Indexes for common queries\nrecipeSchema.index({ title: 'text', tags: 'text' });\nrecipeSchema.index({ author: 1, createdAt: -1 });\n\n\u002F\u002F Virtual fields\nrecipeSchema.virtual('ingredientCount').get(function() {\n  return this.ingredients.length;\n});\n\n\u002F\u002F Pre-save middleware\nrecipeSchema.pre('save', function(next) {\n  if (this.isModified('title')) {\n    this.slug = this.title.toLowerCase().replace(\u002F[^a-z0-9]+\u002Fg, '-');\n  }\n  next();\n});\n\nexport const Recipe = mongoose.models.Recipe || mongoose.model('Recipe', recipeSchema);\n```\n\n### Schema Best Practices\n- Always define `required`, `type`, and validation rules\n- Use `timestamps: true` for automatic `createdAt`\u002F`updatedAt`\n- Add indexes for frequently queried fields\n- Use `enum` for fields with fixed values\n- Define virtuals for computed properties\n- Use middleware (pre\u002Fpost hooks) for side effects\n\n---\n\n## Repository Pattern\n\n```javascript\nclass RecipeRepository {\n  async findAll(filter = {}, options = {}) {\n    const { page = 1, limit = 20, sort = '-createdAt', populate = '' } = options;\n    const skip = (page - 1) * limit;\n\n    const [recipes, total] = await Promise.all([\n      Recipe.find(filter)\n        .sort(sort)\n        .skip(skip)\n        .limit(limit)\n        .populate(populate)\n        .lean(),\n      Recipe.countDocuments(filter),\n    ]);\n\n    return {\n      data: recipes,\n      pagination: {\n        page,\n        limit,\n        total,\n        pages: Math.ceil(total \u002F limit),\n      },\n    };\n  }\n\n  async findById(id) {\n    return Recipe.findById(id).populate('author', 'name avatar').lean();\n  }\n\n  async create(data) {\n    const recipe = new Recipe(data);\n    return recipe.save();\n  }\n\n  async update(id, data) {\n    return Recipe.findByIdAndUpdate(id, data, {\n      new: true,\n      runValidators: true,\n    });\n  }\n\n  async delete(id) {\n    return Recipe.findByIdAndDelete(id);\n  }\n\n  async search(query, options = {}) {\n    return this.findAll(\n      { $text: { $search: query } },\n      { ...options, sort: { score: { $meta: 'textScore' } } }\n    );\n  }\n}\n\nexport const recipeRepository = new RecipeRepository();\n```\n\n---\n\n## Aggregation Pipelines\n\n### Common Patterns\n\n```javascript\n\u002F\u002F Group recipes by tag with counts\nconst tagStats = await Recipe.aggregate([\n  { $match: { isPublished: true } },\n  { $unwind: '$tags' },\n  { $group: { _id: '$tags', count: { $sum: 1 } } },\n  { $sort: { count: -1 } },\n  { $limit: 20 },\n]);\n\n\u002F\u002F Author statistics with lookup\nconst authorStats = await Recipe.aggregate([\n  { $group: {\n    _id: '$author',\n    recipeCount: { $sum: 1 },\n    avgRating: { $avg: '$rating' },\n  }},\n  { $lookup: {\n    from: 'users',\n    localField: '_id',\n    foreignField: '_id',\n    as: 'authorInfo',\n  }},\n  { $unwind: '$authorInfo' },\n  { $project: {\n    name: '$authorInfo.name',\n    recipeCount: 1,\n    avgRating: { $round: ['$avgRating', 1] },\n  }},\n  { $sort: { recipeCount: -1 } },\n]);\n\n\u002F\u002F Date-based analytics\nconst monthlyRecipes = await Recipe.aggregate([\n  { $match: { createdAt: { $gte: new Date('2024-01-01') } } },\n  { $group: {\n    _id: { $dateToString: { format: '%Y-%m', date: '$createdAt' } },\n    count: { $sum: 1 },\n  }},\n  { $sort: { _id: 1 } },\n]);\n```\n\n---\n\n## Atlas Connection\n\n### Connection Setup (Next.js)\n```javascript\nimport mongoose from 'mongoose';\n\nconst MONGODB_URI = process.env.MONGODB_URI;\n\nif (!MONGODB_URI) {\n  throw new Error('MONGODB_URI environment variable is not defined');\n}\n\nlet cached = global.mongoose;\nif (!cached) {\n  cached = global.mongoose = { conn: null, promise: null };\n}\n\nexport async function connectDB() {\n  if (cached.conn) return cached.conn;\n\n  if (!cached.promise) {\n    cached.promise = mongoose.connect(MONGODB_URI, {\n      bufferCommands: false,\n    });\n  }\n\n  cached.conn = await cached.promise;\n  return cached.conn;\n}\n```\n\n### Connection Best Practices\n- Cache connection in development to prevent multiple connections\n- Use `bufferCommands: false` for explicit error handling\n- Set connection pool size via `maxPoolSize` for production\n- Use Atlas connection string with `retryWrites=true&w=majority`\n\n---\n\n## Migration Strategies\n\n### Document Versioning\n```javascript\nconst userSchema = new mongoose.Schema({\n  schemaVersion: { type: Number, default: 2 },\n  \u002F\u002F ... fields\n});\n\nuserSchema.pre('save', function(next) {\n  if (this.schemaVersion \u003C 2) {\n    \u002F\u002F Migrate old fields to new format\n    this.schemaVersion = 2;\n  }\n  next();\n});\n```\n\n### Batch Migration Script\n```javascript\nasync function migrateUsers() {\n  const batchSize = 100;\n  let processed = 0;\n  let batch;\n\n  do {\n    batch = await User.find({ schemaVersion: { $lt: 2 } }).limit(batchSize);\n    for (const user of batch) {\n      user.schemaVersion = 2;\n      await user.save();\n      processed++;\n    }\n    console.log(`Migrated ${processed} users`);\n  } while (batch.length === batchSize);\n}\n```\n\n---\n\n## Performance Tips\n\n- Use `.lean()` for read-only queries (returns plain objects, 5-10x faster)\n- Use `.select()` to return only needed fields\n- Create compound indexes matching your query patterns\n- Use `$project` early in aggregation to reduce working set\n- Avoid `$lookup` in high-frequency queries; denormalize instead\n- Use `explain()` to analyze query performance\n\n## Troubleshooting\n\n| Issue | Solution |\n|-------|----------|\n| Slow queries | Add indexes, use `.lean()`, check with `explain()` |\n| Connection timeouts | Check Atlas network access, increase pool size |\n| Validation errors | Review schema constraints, check middleware order |\n| Duplicate key errors | Ensure unique indexes, handle with try\u002Fcatch |\n| Memory issues | Use cursors for large datasets, limit batch sizes |\n\n---\n\n## Common Pitfalls\n\n- Modeling data like a normalized relational schema by default: MongoDB performance depends on query-driven document shape, not tables-first design.\n- Returning full hydrated documents everywhere: Hydration and over-fetching add cost when a lean projection would do.\n- Adding middleware without explicit write-path tests: Hooks can silently change behavior in create, update, and migration flows.\n\n## References & Resources\n\n### Documentation\n- [Aggregation Reference](.\u002Freferences\u002Faggregation-reference.md) — Pipeline stages, accumulator operators, and common aggregation recipes\n- [Indexing Strategies](.\u002Freferences\u002Findexing-strategies.md) — Index types, ESR rule, compound indexes, and performance analysis\n\n### Scripts\n- [Seed Database](.\u002Fscripts\u002Fseed-database.js) — Zero-dependency MongoDB seeding script with sample recipe data\n\n### Examples\n- [Recipe API Example](.\u002Fexamples\u002Frecipe-api-example.md) — Complete Mongoose + Next.js Recipe CRUD API with models, routes, and validation\n\n---\n\n## Related Skills\n\n- [javascript-development](..\u002Fjavascript-development\u002FSKILL.md): Use it when the workflow also needs modern JavaScript and TypeScript application code.\n- [nextjs-development](..\u002Fnextjs-development\u002FSKILL.md): Use it when the workflow also needs Next.js App Router and server-first React patterns.\n- [sql-development](..\u002Fsql-development\u002FSKILL.md): Use it when the workflow also needs SQL query, schema, and performance tuning work.\n- [code-quality](..\u002Fcode-quality\u002FSKILL.md): Use it when the workflow also needs two-stage review (spec compliance first, then code quality), maintainability, and refactoring guidance.\n","# Mongodb Mongoose\n\n> Optimized for current MongoDB server releases, Mongoose 8.x+, Node.js 22+, and TypeScript 5.5+.\n\nComprehensive guidance for MongoDB database design, Mongoose ODM patterns, and Atlas integration for Node.js\u002FNext.js applications.\n\n- Leverage native parallel subagent dispatch and 200k+ context windows where available.\n\n\n## When to Use This Skill\n\nUse symptom -> action triggers: when one matches, apply this skill and verify with the protocol below.\n\n- Designing MongoDB schemas and data models\n- Building Mongoose models with validation and middleware\n- Implementing the repository pattern for data access\n- Writing aggregation pipelines for complex queries\n- Managing MongoDB Atlas connections and configuration\n- Integrating MongoDB with Next.js API routes\n- Database migration strategies\n\n\n---\n\n\u003C!-- MCP:START -->\n\n\u003C!-- PORTABILITY:START -->\n## Cross-Client Portability\n\nThis skill is written to stay usable across GitHub Copilot, Claude Code, and Codex.\n\n- GitHub Copilot: keep the folder in a Copilot-visible skill path or wrap the\n  workflow in project instructions when folder discovery is unavailable.\n- Claude Code: keep the folder in a local skills directory or a compatible plugin source.\n- Codex: install or sync the folder into\n  `$CODEX_HOME\u002Fskills\u002Fmongodb-mongoose` and restart Codex after major changes.\n\n\u003C!-- PORTABILITY:END -->\n\n## MCP Availability And Fallback\n\nPreferred MCP Server: MongoDB MCP\n\n- Fallback prompt: \"Use the Mongodb Mongoose skill without MCP. Follow the documented local or manual fallback, show the selected tool surface, and report the verification evidence.\"\n- Use `mongosh`, MongoDB Atlas UI, local schema files, and Mongoose model inspection when the MCP server is unavailable.\n- Validate indexes, queries, and aggregation pipelines against a local or staging database before finalizing changes.\n- Do not claim an MCP operation was used when the active host does not expose it.\n\n\u003C!-- MCP:END -->\n\n## Anti-Patterns\n\n- Modeling documents like normalized tables by default: MongoDB performance depends on query-driven shape, not relational purity.\n- Returning full hydrated documents for every request: Over-fetching and hydration overhead accumulate quickly in API paths.\n- Adding middleware without write-path tests: Hooks can silently change create, update, and migration behavior.\n\n## Verification Protocol\n\nBefore claiming \"skill applied successfully\":\n\n1. Pass\u002Ffail: The Mongodb Mongoose implementation names the target runtime, framework version, and affected files.\n2. Pass\u002Ffail: Build, lint, test, or equivalent local validation is run for the changed surface.\n3. Pass\u002Ffail: Edge cases for errors, dependency drift, and environment differences are addressed or explicitly out of scope.\n4. Pressure-test scenario: Apply the workflow to a change that passes happy-path tests but fails one boundary condition.\n5. Success metric: Zero untested success claims; every implementation claim maps to a command or artifact.\n\n## Before and After Example\n\n```javascript\n\u002F\u002F Before\nconst recipes = await Recipe.find({ author: userId }).populate('author');\n\n\u002F\u002F After\nconst recipes = await Recipe.find({ author: userId, isPublished: true })\n  .select({ title: 1, slug: 1, createdAt: 1 })\n  .sort({ createdAt: -1 })\n  .lean();\n```\n\nNarrows the query shape, avoids unnecessary hydration, and aligns the result with the view model actually needed.\n\n## Schema Design\n\n### Data Modeling Principles\n- **Embed** when data is accessed together and has a 1:few relationship\n- **Reference** when data is accessed independently or has a 1:many\u002Fmany:many relationship\n- Design schemas around query patterns, not normalized relational models\n- Use denormalization strategically for read performance\n\n### Mongoose Model Pattern\n```javascript\nimport mongoose from 'mongoose';\n\nconst recipeSchema = new mongoose.Schema({\n  title: {\n    type: String,\n    required: [true, 'Title is required'],\n    trim: true,\n    maxlength: [200, 'Title cannot exceed 200 characters'],\n    index: true,\n  },\n  slug: {\n    type: String,\n    unique: true,\n    lowercase: true,\n  },\n  ingredients: [{\n    name: { type: String, required: true },\n    amount: { type: Number, required: true },\n    unit: { type: String, enum: ['g', 'kg', 'ml', 'l', 'cup', 'tbsp', 'tsp', 'piece'] },\n  }],\n  author: {\n    type: mongoose.Schema.Types.ObjectId,\n    ref: 'User',\n    required: true,\n    index: true,\n  },\n  tags: [{ type: String, lowercase: true, trim: true }],\n  isPublished: { type: Boolean, default: false },\n}, {\n  timestamps: true,\n  toJSON: { virtuals: true },\n  toObject: { virtuals: true },\n});\n\n\u002F\u002F Indexes for common queries\nrecipeSchema.index({ title: 'text', tags: 'text' });\nrecipeSchema.index({ author: 1, createdAt: -1 });\n\n\u002F\u002F Virtual fields\nrecipeSchema.virtual('ingredientCount').get(function() {\n  return this.ingredients.length;\n});\n\n\u002F\u002F Pre-save middleware\nrecipeSchema.pre('save', function(next) {\n  if (this.isModified('title')) {\n    this.slug = this.title.toLowerCase().replace(\u002F[^a-z0-9]+\u002Fg, '-');\n  }\n  next();\n});\n\nexport const Recipe = mongoose.models.Recipe || mongoose.model('Recipe', recipeSchema);\n```\n\n### Schema Best Practices\n- Always define `required`, `type`, and validation rules\n- Use `timestamps: true` for automatic `createdAt`\u002F`updatedAt`\n- Add indexes for frequently queried fields\n- Use `enum` for fields with fixed values\n- Define virtuals for computed properties\n- Use middleware (pre\u002Fpost hooks) for side effects\n\n---\n\n## Repository Pattern\n\n```javascript\nclass RecipeRepository {\n  async findAll(filter = {}, options = {}) {\n    const { page = 1, limit = 20, sort = '-createdAt', populate = '' } = options;\n    const skip = (page - 1) * limit;\n\n    const [recipes, total] = await Promise.all([\n      Recipe.find(filter)\n        .sort(sort)\n        .skip(skip)\n        .limit(limit)\n        .populate(populate)\n        .lean(),\n      Recipe.countDocuments(filter),\n    ]);\n\n    return {\n      data: recipes,\n      pagination: {\n        page,\n        limit,\n        total,\n        pages: Math.ceil(total \u002F limit),\n      },\n    };\n  }\n\n  async findById(id) {\n    return Recipe.findById(id).populate('author', 'name avatar').lean();\n  }\n\n  async create(data) {\n    const recipe = new Recipe(data);\n    return recipe.save();\n  }\n\n  async update(id, data) {\n    return Recipe.findByIdAndUpdate(id, data, {\n      new: true,\n      runValidators: true,\n    });\n  }\n\n  async delete(id) {\n    return Recipe.findByIdAndDelete(id);\n  }\n\n  async search(query, options = {}) {\n    return this.findAll(\n      { $text: { $search: query } },\n      { ...options, sort: { score: { $meta: 'textScore' } } }\n    );\n  }\n}\n\nexport const recipeRepository = new RecipeRepository();\n```\n\n---\n\n## Aggregation Pipelines\n\n### Common Patterns\n\n```javascript\n\u002F\u002F Group recipes by tag with counts\nconst tagStats = await Recipe.aggregate([\n  { $match: { isPublished: true } },\n  { $unwind: '$tags' },\n  { $group: { _id: '$tags', count: { $sum: 1 } } },\n  { $sort: { count: -1 } },\n  { $limit: 20 },\n]);\n\n\u002F\u002F Author statistics with lookup\nconst authorStats = await Recipe.aggregate([\n  { $group: {\n    _id: '$author',\n    recipeCount: { $sum: 1 },\n    avgRating: { $avg: '$rating' },\n  }},\n  { $lookup: {\n    from: 'users',\n    localField: '_id',\n    foreignField: '_id',\n    as: 'authorInfo',\n  }},\n  { $unwind: '$authorInfo' },\n  { $project: {\n    name: '$authorInfo.name',\n    recipeCount: 1,\n    avgRating: { $round: ['$avgRating', 1] },\n  }},\n  { $sort: { recipeCount: -1 } },\n]);\n\n\u002F\u002F Date-based analytics\nconst monthlyRecipes = await Recipe.aggregate([\n  { $match: { createdAt: { $gte: new Date('2024-01-01') } } },\n  { $group: {\n    _id: { $dateToString: { format: '%Y-%m', date: '$createdAt' } },\n    count: { $sum: 1 },\n  }},\n  { $sort: { _id: 1 } },\n]);\n```\n\n---\n\n## Atlas Connection\n\n### Connection Setup (Next.js)\n```javascript\nimport mongoose from 'mongoose';\n\nconst MONGODB_URI = process.env.MONGODB_URI;\n\nif (!MONGODB_URI) {\n  throw new Error('MONGODB_URI environment variable is not defined');\n}\n\nlet cached = global.mongoose;\nif (!cached) {\n  cached = global.mongoose = { conn: null, promise: null };\n}\n\nexport async function connectDB() {\n  if (cached.conn) return cached.conn;\n\n  if (!cached.promise) {\n    cached.promise = mongoose.connect(MONGODB_URI, {\n      bufferCommands: false,\n    });\n  }\n\n  cached.conn = await cached.promise;\n  return cached.conn;\n}\n```\n\n### Connection Best Practices\n- Cache connection in development to prevent multiple connections\n- Use `bufferCommands: false` for explicit error handling\n- Set connection pool size via `maxPoolSize` for production\n- Use Atlas connection string with `retryWrites=true&w=majority`\n\n---\n\n## Migration Strategies\n\n### Document Versioning\n```javascript\nconst userSchema = new mongoose.Schema({\n  schemaVersion: { type: Number, default: 2 },\n  \u002F\u002F ... fields\n});\n\nuserSchema.pre('save', function(next) {\n  if (this.schemaVersion \u003C 2) {\n    \u002F\u002F Migrate old fields to new format\n    this.schemaVersion = 2;\n  }\n  next();\n});\n```\n\n### Batch Migration Script\n```javascript\nasync function migrateUsers() {\n  const batchSize = 100;\n  let processed = 0;\n  let batch;\n\n  do {\n    batch = await User.find({ schemaVersion: { $lt: 2 } }).limit(batchSize);\n    for (const user of batch) {\n      user.schemaVersion = 2;\n      await user.save();\n      processed++;\n    }\n    console.log(`Migrated ${processed} users`);\n  } while (batch.length === batchSize);\n}\n```\n\n---\n\n## Performance Tips\n\n- Use `.lean()` for read-only queries (returns plain objects, 5-10x faster)\n- Use `.select()` to return only needed fields\n- Create compound indexes matching your query patterns\n- Use `$project` early in aggregation to reduce working set\n- Avoid `$lookup` in high-frequency queries; denormalize instead\n- Use `explain()` to analyze query performance\n\n## Troubleshooting\n\n| Issue | Solution |\n|-------|----------|\n| Slow queries | Add indexes, use `.lean()`, check with `explain()` |\n| Connection timeouts | Check Atlas network access, increase pool size |\n| Validation errors | Review schema constraints, check middleware order |\n| Duplicate key errors | Ensure unique indexes, handle with try\u002Fcatch |\n| Memory issues | Use cursors for large datasets, limit batch sizes |\n\n---\n\n## Common Pitfalls\n\n- Modeling data like a normalized relational schema by default: MongoDB performance depends on query-driven document shape, not tables-first design.\n- Returning full hydrated documents everywhere: Hydration and over-fetching add cost when a lean projection would do.\n- Adding middleware without explicit write-path tests: Hooks can silently change behavior in create, update, and migration flows.\n\n## References & Resources\n\n### Documentation\n- [Aggregation Reference](.\u002Freferences\u002Faggregation-reference.md) — Pipeline stages, accumulator operators, and common aggregation recipes\n- [Indexing Strategies](.\u002Freferences\u002Findexing-strategies.md) — Index types, ESR rule, compound indexes, and performance analysis\n\n### Scripts\n- [Seed Database](.\u002Fscripts\u002Fseed-database.js) — Zero-dependency MongoDB seeding script with sample recipe data\n\n### Examples\n- [Recipe API Example](.\u002Fexamples\u002Frecipe-api-example.md) — Complete Mongoose + Next.js Recipe CRUD API with models, routes, and validation\n\n---\n\n## Related Skills\n\n- [javascript-development](..\u002Fjavascript-development\u002FSKILL.md): Use it when the workflow also needs modern JavaScript and TypeScript application code.\n- [nextjs-development](..\u002Fnextjs-development\u002FSKILL.md): Use it when the workflow also needs Next.js App Router and server-first React patterns.\n- [sql-development](..\u002Fsql-development\u002FSKILL.md): Use it when the workflow also needs SQL query, schema, and performance tuning work.\n- [code-quality](..\u002Fcode-quality\u002FSKILL.md): Use it when the workflow also needs two-stage review (spec compliance first, then code quality), maintainability, and refactoring guidance.\n",{"name":5,"tags":25,"version":31,"description":7,"last_updated":32},[26,27,28,29,30],"mongodb","mongoose","development","testing","quality","2.0",1788825600000,"master","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fagent-skills\u002Fmongodb-mongoose",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":44,"prompt":54,"zipAvailable":55},[45,48,51],{"tool":46,"command":47},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill mongodb-mongoose",{"tool":49,"command":50},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill mongodb-mongoose",{"tool":52,"command":53},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill mongodb-mongoose","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fagent-skills\u002Fmongodb-mongoose\u002FSKILL.md",true,[57,63],{"path":58,"resourceType":59,"resourceTypeDesc":60,"sizeBytes":61,"sourceHtmlUrl":62},"CHANGELOG.md","REFERENCE","参考文档",6539,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fagent-skills\u002Fmongodb-mongoose\u002FCHANGELOG.md",{"path":64,"resourceType":65,"resourceTypeDesc":66,"sizeBytes":67,"sourceHtmlUrl":16},"LICENSE.txt","LICENSE","许可证",1070,[69,77,84,91,98,105],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":76},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":76},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":76},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":76},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":76},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":76},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]