前言本项目基于:egg.js安装配置1.安装依赖npminstallegg-mongoose--save2.打开插件#/config/plugin.tsimport{EggPlugin}from'egg';constplugin:EggPlugin={mongoose:{enable:true,package:'egg-mongoose',},};exportdefaultplugin;3.插件配置#/config/config.default.tsimport{EggAppConfig,PowerPartial}from'egg';exportdefault()=>{constconfig={}asPowerPartial;config.mongoose={url:process.env.MONGO_URL||'mongodb://localhost:27017/blog',选项:{poolSize:40,},};返回{...配置,};};本项目lock使用的环境:"egg-mongoose":"3.2.0"node-vv10.5.0splitline,下面是关键使用1.创建模型(Model)eggjs定义/app/model下的数据模型/以我的博客项目为例,假设有一个tag表和article表,article表通过tag_id与tag表关联如下:1.tagtable#/app/model/tag.tsmodule.exports=app=>{constmongoose=app.mongoose;constSchema=mongoose.Schema;constPostSchema=newSchema({tag_name:{type:String,required:true,},created_time:{type:Date,default:newDate(),},updated_time:{type:Date,default:newDate(),},});returnmongoose.model('Tag',PostSchema);};2.article表通过tag_id关联标签表#/app/model/article.tsmodule.exports=app=>{constmongoose=app.mongoose;constSchema=mongoose.Schema;constPostSchema=newSchema({tag_id:{type:Schema.Types.ObjectId,required:true,ref:'Tag',},title:{type:String,required:true,},status:{type:Boolean,默认值:false,},内容:{类型:字符串,默认值:'',},天气:{类型:字符串,默认值:'',},图像:{类型:字符串,默认值:'',},图像:{type:Array,default:[],},pv:{type:Number,default:0,},created_time:{type:Date,default:newDate(),},updated_time:{type:Date,default:新达te(),},});returnmongoose.model('Article',PostSchema);};更多schema的使用:mongooseschema2.简单常用在eggjs中,model层一般是在service层进行操作,返回一个promise,所以可以直接使用await进行同步编程。我们先定义search为查询条件1.新增一篇文章#article是对象constarticle:Article;this.ctx.model.Article.create(文章);添加批次#article对于数组常量文章:Array;this.ctx.model.Article.create(article);2。删除一篇文章this.ctx.model.Article.deleteOne(search);删除多篇文章this.ctx.model.Article.remove(search);3.找一篇文章this.ctx.model.Article.findOne(search);查找多篇文章#搜索为空或空对象返回所有this.ctx.model.Article。查找(搜索);pagesearchskip,limitthis.ctx.model.Article.find(search).sort({_id:-1})#根据创建倒序time.skip(page_size*(current_page-1))#跳过前n条数据.limit(page_size);#限制n条数据4.更改替换文章内容#注意直接替换成new_data#findOneAndUpdate默认返回旧数据#如果需要部分更新,应该使用$set操作符returnawaitthis.ctx.model.Article.findOneAndUpdate(搜索,新数据);返回修改后的最新数据#注意第三个参数returnawaitthis.ctx.model.Article.findOneAndUpdate(search,new_data,{新:真});再分线,下面是重点三。operator$set$set更新指定文档中的一些key,如果该字段不存在则创建#修改文章pv为10000constoperation:any={$set:{pv:10000,},};返回awaitthis.ctx.model.Article.findOneAndUpdate(search,operation);$gt,$lt,$gte,$lte,$ne(>)大于$gt(<)小于$lt(>=)大于或等于$gte(<=)小于或等于$lte(!==)Notequalto$ne#查询pv大于10的文章constsearch={pv:{$gt:1000,},};this.ctx.model.Article.find(搜索);$or,$and,$not,$nor$or满足任意表达式$and同时满足多个表达式$notnot满足表达式$nor不满足任何表达式搜索pv大于10的公开文章const搜索:any={$and:[{pv:{$gt:10}},{status:true},],};this.ctx.model.Article.find(搜索);$inc$inc用于增加和减少现有键的值,仅适用于Number类型对于不存在的key,会自动创建对应的key,value为给定的值文章pv自增const操作:any={$inc:{pv:1,},};this.ctx.model。文章。findOneAndUpdate(搜索,操作);$push,$pull$push在已有数组末尾添加一个元素,如果没有则创建一个新数组$pull会删除数组中符合条件的元素constoperation:any={$push:{images:{content:'helloworld',},},};awaitthis.ctx.model.Article.findOneAndUpdate(search,operation);常量操作:any={$pull:{images:{content:'helloworld',},},};awaitthis.ctx.model.Article.findOneAndUpdate(search,operation);$in,$nin$in包含$nin但不包含$in类似于jsAraayincludesmethod,andarray任意一个值等于在[1,2,3]中查找pv文章constsearch:any={pv:{$in:[1,2,3],},};this.ctx.model.Article.find(search);$type$type匹配数据类型详细类型请:MongoDB$typeoperatormatchesstatus字段类型为booleanconstsearch:any={status:{$type:8,},};this.ctx.model。Article.find(search);$exists$exists判断字段是否存在查找status字段存在的文章constsearch:any={status:{$exists:true,},};this.ctx.model.Article.找到(SEarch);$regex$regex正则匹配内容正则匹配内容123constsearch:any={content:{$regex:'123',$options:'i'},};this.ctx.model.Article.find(search);其实也可以直接使用字面量的const搜索:any={content:/123/g,};this.ctx.model.Article.find(搜索);$where$where类似于mysql的wheretofindpvArticlesgreaterthan20constsearch:any={$where:'this.pv>20',};this.ctx.model.Article.find(search);4.aggregate聚合MongoDB的聚合管道将MongoDB文档放在一个管道中处理后将结果传递给下一个管道处理管道操作是可重复的。常用的管道操作符:1.$match$match用于过滤数据,只输出满足条件的文档。this.ctx.model.Article.aggregate([{$match:search},]);2.$project$project用于修改输入文档的结构,可以通过重命名、增删字段来修改文档结构,只输出内容字段this.ctx.model.Article.aggregate([{$match:search},{$project:{content:1,},},]);3.$limit,$skip$limi:限制返回的文档数量$skip:跳过指定数量的文档常用的分页搜索this.ctx.model.Article.aggregate([{$match:search},{$skip:page_size*(current_page-1)},{$limit:page_size},]);4.$group$group对集合中的文档进行分组,用于统计结果。类似于mysqlgroupby统计每个标签count的文章总数this.ctx.model.Article.aggregate([{$group:{_id:'$tag_id',count:{$sum:1,},},},]);5.$sort$sort对输入文档进行排序,并按照文章修改时间倒序输出this.ctx.model.Article.aggregate([{$match:search},{$sort:{updated_time:-1}},]);6.$lookup,$unwind$unwind将Array类型字段拆分为多块,每块包含数组中的一个值。$lookup是3.2版本新增的,有几个实现联表查询的参数:语法解释来自源数据表localField待联数据表foreignFieldJoin数据表匹配字段为输出文档的新值名称查找文章详情,根据tag_idthis.ctx.model.Article.aggregate([{$lookup:{from:'tags',localField:'tag_id',foreignField:'_id',as:'tag_info',},},{$unwind:'$tag_info'},]);END