乐闻世界logo
搜索文章和话题

Mongoose Model 有哪些常用的 CRUD 操作方法?

2月22日 20:12

Mongoose Model 是由 Schema 编译而成的构造函数,用于创建和操作 MongoDB 文档。Model 实例代表数据库中的文档,并提供了丰富的 CRUD 操作方法。

创建 Model

javascript
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, email: String, age: Number }); // 创建 Model,第一个参数是集合名称(会自动转为复数) const User = mongoose.model('User', userSchema);

Model 的主要方法

创建文档

javascript
// 方法1:使用 new 关键字 const user = new User({ name: 'John', email: 'john@example.com' }); await user.save(); // 方法2:使用 create 方法 const user = await User.create({ name: 'John', email: 'john@example.com' }); // 方法3:使用 insertMany const users = await User.insertMany([ { name: 'John', email: 'john@example.com' }, { name: 'Jane', email: 'jane@example.com' } ]);

查询文档

javascript
// 查找所有 const users = await User.find(); // 条件查询 const user = await User.findOne({ email: 'john@example.com' }); const users = await User.find({ age: { $gte: 18 } }); // 按 ID 查找 const user = await User.findById('507f1f77bcf86cd799439011'); // 链式查询 const users = await User.find({ age: { $gte: 18 } }) .select('name email') .sort({ name: 1 }) .limit(10);

更新文档

javascript
// 更新单个文档 const user = await User.findByIdAndUpdate( '507f1f77bcf86cd799439011', { age: 25 }, { new: true } // 返回更新后的文档 ); // 条件更新 const result = await User.updateOne( { email: 'john@example.com' }, { age: 25 } ); // 批量更新 const result = await User.updateMany( { age: { $lt: 18 } }, { status: 'minor' } ); // findOneAndUpdate const user = await User.findOneAndUpdate( { email: 'john@example.com' }, { age: 25 }, { new: true } );

删除文档

javascript
// 按 ID 删除 const user = await User.findByIdAndDelete('507f1f77bcf86cd799439011'); // 条件删除 const result = await User.deleteOne({ email: 'john@example.com' }); // 批量删除 const result = await User.deleteMany({ age: { $lt: 18 } }); // findOneAndDelete const user = await User.findOneAndDelete({ email: 'john@example.com' });

统计文档

javascript
const count = await User.countDocuments({ age: { $gte: 18 } }); const count = await User.estimatedDocumentCount(); // 快速估算

Model 的静态方法

可以在 Schema 上添加自定义静态方法:

javascript
userSchema.statics.findByEmail = function(email) { return this.findOne({ email }); }; const User = mongoose.model('User', userSchema); const user = await User.findByEmail('john@example.com');
标签:Mongoose