Mongoose 在egg中的使用详解

2020-06-12 12:59:54刘景俊

可以看到,通过this.ctx.model.Book就可以获取到Book的model并且可以调用mongoose需要的方法,例如populate、find、and、sort、skip、limit 等等。

5、egg-Mongoose常用的方法

增加数据

this.ctx.model.Book.create(data,callback);

其中data为json数据结构,callback为操作后的回调函数

查询数据

获取所有数据,返回是一个数组

this.ctx.model.Book.find()

获取一个数据,返回是一个对象

this.ctx.model.Book.findOne()

条件查询

this.ctx.model.Article.find(conditions,callback);

其中conditions为查询的条件,callback为回调函数
conditions有一下几种情况:

具体数据:

this.ctx.model.Book.find
(
{_id:5c4a19fb87ba4002a47ac4d, name: "射雕英雄传" 
}
, callback)
;

条件查询:

"$lt" 小于
"$lte" 小于等于
"$gt" 大于
"$gte" 大于等于
"$ne" 不等于
// 查询价格大于100小于200的书籍数组
this.ctx.model.Book.find({ "price": { $get:100 , $lte:200 }); 

或查询 OR

"$in" 一个键对应多个值
"$nin" 同上取反, 一个键不对应指定值
"$or" 多个条件匹配, 可以嵌套 $in 使用
"$not" 同上取反, 查询与特定模式不匹配的文档

this.ctx.model.Book.find({"name":{ $in: ["射雕","倚天"]} );

删除数据

this.ctx.model.Book.remove(conditions,callback);

更新数据

this.ctx.model.Book.update(conditions, update, callback)

conditions为条件,update是更新的值对象

排序

this.ctx.model.Book.sort({ create_time: -1 });

其中-1表示降序返回。 1表示升序返回

限制数量

this.ctx.model.Book.limit(number);

number表示限制的个数

跳过文档返回

this.ctx.model.Book.skip(number);

number表示跳过的个数,skip经常搭配limit实现分页的功能

条件数组and

在find后面可使用and对查询结果进行进一步条件筛选,相当于并且的意思。

const search_term = {
 $or: [
 { desc: { $regex: desc ? desc : '', $options: '$i' } },
 { name: { $regex: desc ? desc : '', $options: '$i' } },
 { author: { $regex: desc ? desc : '', $options: '$i' } },
 { press: { $regex: desc ? desc : '', $options: '$i' } },
 ],
 };
 this.ctx.model.Book.find().and(search_term)

关联查询populate

// 在model中配置字段时候指定关联的表名,就可以通过populate来进行表的关联查询
user: { /* 书籍发布者id */
 type: Schema.Types.ObjectId,
 ref: 'User',
 },
 
this.ctx.model.Book.find()
 .populate({
 path: 'user',
 select: { name: 1, image: 1 }
 })