概述
Mongoose 在 MongoDB 之上提供 schema、类型转换、校验和中间件,让文档数据拥有显式结构。
核心 API
connect:建立 MongoDB 连接,可配置连接池和超时。Schema:定义文档结构、字段类型、默认值、校验器和索引。model:把 schema 编译为带 CRUD 查询方法的 Model 类。find:按过滤条件查询,并可链式 sort、limit 和 populate。pre / post hooks:注册在文档或查询操作前后运行的中间件。
const orderSchema = new Schema({
customerId: { type: Schema.Types.ObjectId, required: true, index: true },
total: { type: Number, min: 0 },
}, { timestamps: true });
const Order = model('Order', orderSchema);
await Order.find({ customerId }).sort({ createdAt: -1 }).limit(20);
使用注意
为查询字段建索引,并用 explain 验证。校验器不能替代服务端授权。populate 可能引入额外查询,注意 N+1。连接错误和断线要有处理策略。
验证方式
用内存 MongoDB 验证 schema 校验、查询过滤、索引和中间件触发顺序。