本项目基于: egg.jshtml
npm install egg-mongoose --save
# /config/plugin.ts import { EggPlugin } from 'egg'; const plugin: EggPlugin = { mongoose: { enable: true, package: 'egg-mongoose', }, }; export default plugin;
# /config/config.default.ts import { EggAppConfig, PowerPartial } from 'egg'; export default () => { const config = {} as PowerPartial<EggAppConfig>; config.mongoose = { url: process.env.MONGO_URL || 'mongodb://localhost:27017/blog', options: { poolSize: 40, }, }; return { ...config, }; };
本项目锁使用的环境:node
"egg-mongoose": "3.2.0" node -v v10.5.0
分割线,下面是重点mysql
eggjs 在 /app/model/ 下定义数据模型sql
以个人 blog 项目为例,假设有一个 tag 表、article 表,article 表经过 tag_id 关联 tag 表以下:mongodb
# /app/model/tag.ts module.exports = app => { const mongoose = app.mongoose; const Schema = mongoose.Schema; const PostSchema = new Schema({ tag_name: { type: String, required: true, }, created_time: { type: Date, default: new Date(), }, updated_time: { type: Date, default: new Date(), }, }); return mongoose.model('Tag', PostSchema); };
经过 tag_id 关联 tag 表npm
# /app/model/article.ts module.exports = app => { const mongoose = app.mongoose; const Schema = mongoose.Schema; const PostSchema = new Schema({ tag_id: { type: Schema.Types.ObjectId, required: true, ref: 'Tag', }, title: { type: String, required: true, }, status: { type: Boolean, default: false, }, content: { type: String, default: '', }, weather: { type: String, default: '', }, image: { type: String, default: '', }, images: { type: Array, default: [], }, pv: { type: Number, default: 0, }, created_time: { type: Date, default: new Date(), }, updated_time: { type: Date, default: new Date(), }, }); return mongoose.model('Article', PostSchema); };
更多 schema 使用:mongoose schema编程
eggjs 中,通常在 service 层操做 model 层,返回的是一个 promise,so 能够直接用 await 同步编程数组
咱们先定义 search 为查询条件promise
新增一篇文章bash
# article 为对象 const article: Article; this.ctx.model.Article.create(article);
批量新增
# article 为数组 const article: Array<Article>; this.ctx.model.Article.create(article);
删除一篇文章
this.ctx.model.Article.deleteOne(search);
删除多篇文章
this.ctx.model.Article.remove(search);
查找一篇文章
this.ctx.model.Article.findOne(search);
查找多篇
# search 为空 或者空对象返回所有 this.ctx.model.Article.find(search);
分页查找 skip、limit
this.ctx.model.Article.find(search) .sort({ _id: -1 }) # 按照建立时间倒序 .skip(page_size * (current_page - 1)) # 跳过前n个数据 .limit(page_size); # 限制n个数据
替换文章内容
# 注意,是直接所有替换为 new_data # findOneAndUpdate默认返回旧的数据 # 若须要部分更新,应使用 $set 操做符 return await this.ctx.model.Article.findOneAndUpdate(search, new_data);
返回修改后最新的数据
# 注意第三个参数 return await this.ctx.model.Article.findOneAndUpdate(search, new_data, { new: true });
再次分割线,下面是重点中的重点
$set 对指定文档中的某些键进行更新,若是这个字段不存在则建立它
# 修改文章 pv为 10000 const operation: any = { $set: { pv: 10000, }, }; return await this.ctx.model.Article.findOneAndUpdate(search, operation);
# 查pv大于10的文章 const search = { pv: { $gt: 1000, }, }; this.ctx.model.Article.find(search);
查找 pv 大于 10 且公开的文章
const search: any = { $and: [ { pv: { $gt: 10 } }, { status: true }, ], }; this.ctx.model.Article.find(search);
$inc 用来增长和减小已有键的值,只能用于 Number 类型。对于不存在的键,会自动建立相应的键,而且值为给定的值
文章 pv 自增
const operation: any = { $inc: { pv: 1, }, }; this.ctx.model.Article.findOneAndUpdate(search, operation);
$push 向已有的数组末尾添加一个元素,若是没有就建立一个新的数组$pull 会删除掉数组中符合条件的元素
const operation: any = { $push: { images: { content: 'hello world', }, }, }; await this.ctx.model.Article.findOneAndUpdate(search, operation); const operation: any = { $pull: { images: { content: 'hello world', }, }, }; await this.ctx.model.Article.findOneAndUpdate(search, operation);
$in 相似与 js Araay includes 方法,与数组中任意一个值相等
查找 pv 在[1,2,3]的文章
const search: any = { pv: { $in: [ 1, 2, 3 ], }, }; this.ctx.model.Article.find(search);
$type 匹配数据类型
详细的类型请:MongoDB $type 操做符
匹配 status 字段类型为 boolean
const search: any = { status: { $type: 8, }, }; this.ctx.model.Article.find(search);
$exists 判断字段是否存在
查找 status 字段存在的文章
const search: any = { status: { $exists: true, }, }; this.ctx.model.Article.find(search);
$regex 正则匹配内容
正则匹配内容 123
const search: any = { content: { $regex: '123', $options: 'i' }, }; this.ctx.model.Article.find(search);
实际上,也能够直接用字面量
const search: any = { content: /123/g, }; this.ctx.model.Article.find(search);
$where 相似于 mysql 的 where
查找 pv 大于 20 的文章
const search: any = { $where: 'this.pv>20', }; this.ctx.model.Article.find(search);
MongoDB 的聚合管道将 MongoDB 文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操做是能够重复的。
经常使用的管道操做符:
$match 用于过滤数据,只输出符合条件的文档。
this.ctx.model.Article.aggregate([ { $match: search }, ]);
$project 用于修改输入文档的结构,能够用来重命名、增长或删除域
修改文档结构,只输出 content 字段
this.ctx.model.Article.aggregate([ { $match: search }, { $project: { content: 1, }, }, ]);
经常使用的分页查找
this.ctx.model.Article.aggregate([ { $match: search }, { $skip: page_size * (current_page - 1) }, { $limit: page_size }, ]);
$group 将集合中的文档分组,用于统计结果。相似于 mysql group by
统计每一个标签的文章总数 count
this.ctx.model.Article.aggregate([ { $group: { _id: '$tag_id', count: { $sum: 1, }, }, }, ]);
$sort 将输入文档排序后输出
按照文章修改时间倒序
this.ctx.model.Article.aggregate([ { $match: search }, { $sort: { updated_time: -1 } }, ]);
有几个参数:
语法 | 解释 |
---|---|
from | 源数据表 |
localField | 待 Join 的数据表 |
foreignField | Join 的数据表的 match 字段 |
as | 为输出文档的新增值命名 |
查找文章详情,根据 tag_id 查找 tag 表的详情
this.ctx.model.Article.aggregate([ { $lookup: { from: 'tags', localField: 'tag_id', foreignField: '_id', as: 'tag_info', }, }, { $unwind: '$tag_info' }, ]);
END