多表查询分页可以使用mongoose-aggregate-paginate-v2
interface表Model
const aggregatePaginate = require('mongoose-aggregate-paginate-v2');module.exports = app => {const mongoose = app.mongoose;const schema = new mongoose.Schema({// 自增IDid: { type: Number, unique: true },// ...省略// 创建人createBy: { type: String },// 更新时间updateTime: { type: String },// 更新人updateBy: { type: String },});schema.plugin(aggregatePaginate);// mongoose.model(名称,数据,表名)return mongoose.model('system Interface', schema, 'interface');};
user表Model
const aggregatePaginate = require('mongoose-aggregate-paginate-v2');module.exports = app => {const mongoose = app.mongoose;const schema = new mongoose.Schema({// 自增IDid: { type: Number, unique: true },// 用户唯一IDuuid: { type: String, unique: true },// 用户角色roleId: { type: Number },// 用户名-用于登录,找回密码userName: { type: String, unique: true },// ...省略});schema.plugin(aggregatePaginate);// mongoose.model(名称,数据,表名)return mongoose.model('user-list', schema, 'user');};
| 命令 | 功能描述 |
|---|---|
| $project | 指定输出文档里的字段. |
| $match | 选择要处理的文档,与fine()类似。 |
| $limit | 限制传递给下一步的文档数量。 |
| $skip | 跳过一定数量的文档。 |
| $unwind | 扩展数组,为每个数组入口生成一个输出文档。 |
| $group | 根据key来分组文档。 |
| $sort | 排序文档。 |
| $geoNear | 选择某个地理位置附近的的文档。 |
| $out | 把管道的结果写入某个集合。 |
| $redact | 控制特定数据的访问。 |
| $lookup | 多表关联(3.2版本新增) |
这里就是使用$lookup进行多表关联查询,$lookup可以设置多个,通过不同的字段,关联不同的表
async list(page, pageSize, query, select) {const { ctx } = this;// 关联查询user表const aggregateQuery = ctx.model.System.Interface.aggregate([{$lookup: {// 关联的表from: 'user',// 当前表关联的字段(如现在的Interface表)localField: 'createBy',// 关联的表的字段(user表的userName字段)foreignField: 'userName',// 查询出来的关联数据,存放在'createUser'字段中as: 'createUser',},},{$lookup: {from: 'user',localField: 'updateBy',foreignField: 'userName',as: 'updateUser',},},{// $project:设置0隐藏某些字段 ,让其不返回$project: {createUser: {_id: 0,__v: 0,uuid: 0,password: 0,updateBy: 0,updateTime: 0,createTime: 0,createBy: 0,registerTime: 0,},updateUser: {_id: 0,__v: 0,uuid: 0,password: 0,updateBy: 0,updateTime: 0,createTime: 0,createBy: 0,registerTime: 0,},__v: 0,...select,},},]);const list = await ctx.model.System.Interface.aggregatePaginate(aggregateQuery,{page: Number(page) || 1,// 每页数limit: Number(pageSize) || 10,sort: { menuId: 1 },},);return list;}
Mongodb批量操作,如批量删除,批量修改字段
mongodb多表关联查询
捕获save报错,返回controller
UUID,是Universally Unique Identifier的缩写,UUID出现的目的,是为了让分布式系统可以不借助中心节点,就可以生成UUID来标识一些唯一的信息;