mcpField
M
mongoose-mongodb

mongoose-mongodb

github.com/pluginagentmarketplace数据与数据库2694 次安装42 周前更新
代码仓库

关于 mongoose-mongodb

mongoose-mongodb 是面向 Node.js 开发者的 Mongoose 与 MongoDB 学习技能,涵盖连接、建模和查询,并从基础 CRUD 延伸至高级数据库模式。

主要功能

  1. 01连接设置与错误处理
  2. 02Schema 和模型定义
  3. 03CRUD 操作与查询
  4. 04关联与填充
  5. 05索引、中间件和虚拟属性
  6. 06聚合与事务

适用场景

  1. 01将 Node.js 应用连接到 MongoDB
  2. 02建模并验证应用数据
  3. 03查询关联文档
  4. 04优化常用数据库操作

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/pluginagentmarketplace/custom-plugin-nodejs --skill mongoose-mongodb

安装后在 Claude Code 中输入/mongoose-mongodb确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/
config.yaml
references/
GUIDE.md
scripts/
helper.py

详细介绍

Mongoose 与 MongoDB 技能

使用 Mongoose(优雅的对象建模库)掌握在 Node.js 中集成 MongoDB 数据库。

快速入门

通过 4 个步骤完成连接和 CRUD:

  1. 安装 - npm install mongoose
  2. 连接 - mongoose.connect(uri)
  3. 定义 Schema - 创建数据模型
  4. CRUD - 创建、读取、更新、删除

核心概念

连接设置
const mongoose = require('mongoose');

mongoose.connect(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

mongoose.connection.on('connected', () => {
  console.log('MongoDB connected');
});
Schema 与 Model
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 } });
关系与填充
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
  • ✅ 创建 Schema 和 Model
  • ✅ CRUD 操作
  • ✅ 基本查询
中级(4-5 周)
  • ✅ 关系与填充
  • ✅ 验证和中间件
  • ✅ 用于提升性能的索引
  • ✅ 查询运算符
高级(6-8 周)
  • ✅ 聚合管道
  • ✅ 事务
  • ✅ Schema 设计模式
  • ✅ 性能优化

高级功能

索引
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()(性能更佳)
  • ✅ 在 Schema 层验证数据
  • ✅ 对多文档操作使用事务
  • ✅ 妥善处理连接错误
  • ✅ 应用关闭时关闭连接

适用场景

以下情况适合使用 MongoDB 和 Mongoose:

  • 构建 Node.js 应用
  • 需要灵活的 Schema(基于文档)
  • 处理大量数据
  • 快速原型设计和迭代
  • 处理类似 JSON 的数据

相关技能

  • Express REST API(连接到 MongoDB)
  • 异步编程(异步数据库操作)
  • JWT 身份验证(存储用户)
  • Jest 测试(测试数据库操作)

资源

评论

支持 Markdown