Token导航 LogoToken导航TokenDH.com
研究检索敏感数据github未标认证来源可访问许可证需确认审计通过

mongodb-mongooseMongoDB mongoose 搜索

Agent Skill

用于辅助数据库表结构、查询语句、迁移脚本和数据维护任务。它适合让 Agent 分析 schema、编写 SQL、排查查询问题、整理索引或生成迁移建议。使用时需要明确数据库类型、连接环境和目标表,区分只读分析与写入变更;涉及删除、更新、迁移和批量导入时,应优先 dry-run、备份或事务保护,避免误操作。

总安装

297

周安装

12

GitHub Stars

3

下载量

93
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:mongodb-mongoose(MongoDB mongoose 搜索)
来源仓库:https://github.com/practicalswan/agent-skills
仓库路径:skills/mongodb-mongoose
安装命令:
npx skills add https://github.com/practicalswan/agent-skills --skill mongodb-mongoose
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/practicalswan/agent-skills --skill mongodb-mongoose

简介

用于查找、检索和筛选相关信息。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中快速定位候选结果。
  • 可结合关键词、任务场景或来源线索进行信息筛选。
  • 安装前建议确认权限范围和维护状态,避免触发不必要操作。
  • 可通过 npx skills add 命令从指定 GitHub 仓库安装使用。

SKILL.md

Skill Paths

  • Workspace skills: .github/skills/
  • Global skills: C:/Users/LOQ/.codex/skills/ for Codex or C:/Users/LOQ/.agents/skills/ for the shared mirror

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

When to Use This Skill

  • 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

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

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

Cross-Client Portability

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

  • GitHub Copilot: keep the folder in a Copilot-visible skill or plugin path, or wrap the workflow as project instructions if the host does not support portable skill folders directly.
  • Claude Code: keep the folder in a local skills directory or a compatible plugin or marketplace source.
  • Codex: install or sync the folder into $CODEX_HOME/skills/<skill-name> and restart Codex after major changes.
  • Gemini CLI: this repository generates a project command named /skills:mongodb-mongoose from this skill. Rebuild commands with python scripts/export-gemini-skill.py mongodb-mongoose and then run /commands reload inside Gemini CLI.

MCP Availability And Fallback

Preferred MCP servers for this skill:

  • MongoDB MCP (primary)

If MCP is unavailable in the current host:

  • 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.

Related Skills

SkillRelationship
nestjsNestJS backend using Mongoose models
javascript-developmentJS patterns for database integration
sql-developmentAlternative relational database approach

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.84%
按下载量换算32

Claude

30.86%
按下载量换算29

Cursor

18.89%
按下载量换算18

Gemini CLI

9.47%
按下载量换算9

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills