mongoose-mongodb

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Mongoose & MongoDB Skill

Mongoose & MongoDB 技能

Master MongoDB database integration in Node.js with Mongoose, the elegant object modeling library.
在Node.js中通过Mongoose这款优雅的对象建模库,掌握MongoDB数据库集成。

Quick Start

快速开始

Connect and CRUD in 4 steps:
  1. Install -
    npm install mongoose
  2. Connect -
    mongoose.connect(uri)
  3. Define Schema - Create data models
  4. CRUD - Create, Read, Update, Delete
只需4步完成连接与CRUD操作:
  1. 安装 -
    npm install mongoose
  2. 连接 -
    mongoose.connect(uri)
  3. 定义Schema - 创建数据模型
  4. CRUD - 创建、读取、更新、删除

Core Concepts

核心概念

Connection Setup

连接配置

javascript
const mongoose = require('mongoose');

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

mongoose.connection.on('connected', () => {
  console.log('MongoDB connected');
});
javascript
const mongoose = require('mongoose');

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

mongoose.connection.on('connected', () => {
  console.log('MongoDB connected');
});

Schema & Model

Schema与模型

javascript
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);
javascript
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 Operations

CRUD操作

javascript
// Create
const user = await User.create({
  name: 'John Doe',
  email: 'john@example.com'
});

// Read
const users = await User.find({ age: { $gte: 18 } });
const user = await User.findById(id);
const user = await User.findOne({ email: 'john@example.com' });

// 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 } });
javascript
// Create
const user = await User.create({
  name: 'John Doe',
  email: 'john@example.com'
});

// Read
const users = await User.find({ age: { $gte: 18 } });
const user = await User.findById(id);
const user = await User.findOne({ email: 'john@example.com' });

// 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 } });

Relationships & Population

数据关联与填充

javascript
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
javascript
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

Learning Path

学习路径

Beginner (2-3 weeks)

入门阶段(2-3周)

  • ✅ Install MongoDB and Mongoose
  • ✅ Create schemas and models
  • ✅ CRUD operations
  • ✅ Basic queries
  • ✅ 安装MongoDB与Mongoose
  • ✅ 创建Schema与模型
  • ✅ CRUD操作
  • ✅ 基础查询

Intermediate (4-5 weeks)

进阶阶段(4-5周)

  • ✅ Relationships and population
  • ✅ Validation and middleware
  • ✅ Indexes for performance
  • ✅ Query operators
  • ✅ 数据关联与填充
  • ✅ 验证与中间件
  • ✅ 性能优化索引
  • ✅ 查询操作符

Advanced (6-8 weeks)

高级阶段(6-8周)

  • ✅ Aggregation pipelines
  • ✅ Transactions
  • ✅ Schema design patterns
  • ✅ Performance optimization
  • ✅ 聚合管道
  • ✅ 事务处理
  • ✅ Schema设计模式
  • ✅ 性能优化

Advanced Features

高级功能

Indexes

索引

javascript
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ name: 1, age: -1 });
javascript
userSchema.index({ email: 1 }, { unique: true });
userSchema.index({ name: 1, age: -1 });

Middleware (Hooks)

中间件(钩子)

javascript
userSchema.pre('save', async function(next) {
  if (this.isModified('password')) {
    this.password = await bcrypt.hash(this.password, 10);
  }
  next();
});
javascript
userSchema.pre('save', async function(next) {
  if (this.isModified('password')) {
    this.password = await bcrypt.hash(this.password, 10);
  }
  next();
});

Virtual Properties

虚拟属性

javascript
userSchema.virtual('fullName').get(function() {
  return `${this.firstName} ${this.lastName}`;
});
javascript
userSchema.virtual('fullName').get(function() {
  return `${this.firstName} ${this.lastName}`;
});

Aggregation Pipeline

聚合管道

javascript
const stats = await User.aggregate([
  { $match: { age: { $gte: 18 } } },
  { $group: {
    _id: '$role',
    count: { $sum: 1 },
    avgAge: { $avg: '$age' }
  }},
  { $sort: { count: -1 } }
]);
javascript
const stats = await User.aggregate([
  { $match: { age: { $gte: 18 } } },
  { $group: {
    _id: '$role',
    count: { $sum: 1 },
    avgAge: { $avg: '$age' }
  }},
  { $sort: { count: -1 } }
]);

Query Operators

查询操作符

javascript
// 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$/ })
javascript
// 比较操作符
User.find({ age: { $gt: 18 } })     // 大于
User.find({ age: { $gte: 18 } })    // 大于等于
User.find({ age: { $lt: 65 } })     // 小于
User.find({ age: { $lte: 65 } })    // 小于等于
User.find({ age: { $ne: 30 } })     // 不等于

// 逻辑操作符
User.find({ $and: [{ age: { $gte: 18 } }, { age: { $lte: 65 } }] })
User.find({ $or: [{ role: 'admin' }, { role: 'moderator' }] })

// 数组操作符
User.find({ tags: { $in: ['node', 'mongodb'] } })
User.find({ tags: { $nin: ['deprecated'] } })

// 正则表达式
User.find({ email: /gmail\.com$/ })

Best Practices

最佳实践

  • ✅ Use environment variables for connection strings
  • ✅ Create indexes for frequently queried fields
  • ✅ Use
    lean()
    for read-only queries (better performance)
  • ✅ Validate data at schema level
  • ✅ Use transactions for multi-document operations
  • ✅ Handle connection errors properly
  • ✅ Close connections on app shutdown
  • ✅ 使用环境变量存储连接字符串
  • ✅ 为频繁查询的字段创建索引
  • ✅ 对只读查询使用
    lean()
    (提升性能)
  • ✅ 在Schema层面验证数据
  • ✅ 多文档操作使用事务
  • ✅ 妥善处理连接错误
  • ✅ 应用关闭时关闭数据库连接

When to Use

适用场景

Use MongoDB with Mongoose when:
  • Building Node.js applications
  • Need flexible schema (document-based)
  • Handling large volumes of data
  • Rapid prototyping and iteration
  • Working with JSON-like data
在以下场景使用MongoDB与Mongoose:
  • 构建Node.js应用
  • 需要灵活的Schema(基于文档的数据库)
  • 处理大规模数据
  • 快速原型开发与迭代
  • 处理类JSON格式数据

Related Skills

相关技能

  • Express REST API (connect to MongoDB)
  • Async Programming (async database operations)
  • JWT Authentication (store users)
  • Jest Testing (test database operations)
  • Express REST API(与MongoDB连接)
  • 异步编程(异步数据库操作)
  • JWT认证(存储用户信息)
  • Jest测试(测试数据库操作)

Resources

参考资源