mongoose的常用的封装方法
时间: 2023-12-26 11:11:08 浏览: 77
以下是一些常用的 Mongoose 封装方法:
1. 连接 MongoDB 数据库:
```javascript
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myapp', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
```
2. 定义模型:
```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
age: Number,
});
const User = mongoose.model('User', UserSchema);
```
3. 创建文档:
```javascript
const user = new User({ name: 'Alice', age: 26 });
user.save();
```
4. 查询文档:
```javascript
User.findOne({ name: 'Alice' }, (err, user) => {
console.log(user);
});
```
5. 更新文档:
```javascript
User.updateOne({ name: 'Alice' }, { age: 27 }, (err, res) => {
console.log(res);
});
```
6. 删除文档:
```javascript
User.deleteOne({ name: 'Alice' }, (err, res) => {
console.log(res);
});
```
除了以上基本操作,还可以封装一些常用的操作,例如:
1. 分页查询:
```javascript
const query = User.find().skip((pageNum - 1) * pageSize).limit(pageSize);
const users = await query.exec();
```
2. 根据条件查询:
```javascript
const query = User.find({ age: { $gt: 20 } });
const users = await query.exec();
```
3. 统计数量:
```javascript
const count = await User.countDocuments({ age: { $gt: 20 } });
```
4. 排序:
```javascript
const query = User.find().sort({ age: -1 });
const users = await query.exec();
```
5. 聚合查询:
```javascript
const result = await User.aggregate([
{
$match: { age: { $gt: 20 } },
},
{
$group: {
_id: '$name',
total: { $sum: 1 },
},
},
]);
```
以上是一些常用的 Mongoose 封装方法,可以根据实际需求进行封装和扩展。
阅读全文