egg中egg-mongoose使用摘记

1,705 阅读3分钟

安装

$ yarn add egg-mongoose

配置

// {workplace}/config/config.default.js

module.exports = appInfo => {
  const config = exports = {};
  // mogodb设置  
  config.mongoose = {
    clients: {
      glui: { url: 'mongodb://localhost:27017/glui', options: { useNewUrlParser: true, }, },
      easymock: { url: 'mongodb://localhost:27017/easy-mock', options: { useNewUrlParser: true, }, }
    }
  };
  return config;
};

定义数据表

// {workplace}/app/model/user.js

'use strict';
module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const conn = app.mongooseDB.get('glui');
  const schema = new Schema({
    nick_name: String,
    head_img: String,
    name: String,
    password: String,
    wechat: String,
    open_id: String,
    machine_ip: String,
    machine_name: String,
    worker_no: String,
    flag: {
      type: Boolean,
      default: true
    },
    create_at: {
      type: Date,
      default: Date.now
    }
  })
  schema.index(
    { name: 1 },
    { unique: true }
  );
  return conn.model('User', schema);
}

mongoose方法

class GluiController extends Controller {
  async test() {
    const ctx = this.ctx;

    /** 一 增加数据 */
    // post为json数据结构,callback为操作后的回调函数
    ctx.model.User.create(post, callback);


    /** 二 查询数据 */
    // 获取所有数据,返回是一个数组
    ctx.model.User.find()
    // 获取一个数据,返回是一个对象
    ctx.model.User.findOne()


    // 条件查询
    ctx.model.User.find(conditions, callback);
    // condition有如下形式
    // 1)根据具体数据进行查询
    ctx.model.User.find({ _id: '5ba05c89b1f3b6355e1d635e', name: 'Alioth' }, callback);
    // 2)条件查询
    // "$lt"	小于
    // "$lte"	小于等于
    // "$gt"	大于
    // "$gte"	大于等于
    // "$ne"	不等于
    ctx.model.User.find({ create_at: { $gte: new Date(2019, 7, 5), $lte: new Date(2019, 7, 6) } })
    // 3)或查询 OR
    // "$in" 一个键对应多个值
    // "$nin" 同上取反, 一个键不对应指定值
    // "$or" 多个条件匹配, 可以嵌套 $in 使用
    // "$not"	同上取反, 查询与特定模式不匹配的文档
    ctx.model.User.find({ name: { $in: ['Alioth', 'Jodie'] } });
    ctx.model.User.find({ $or: [{ _id: '5ba05c89b1f3b6355e1d635e' }, { name: 'Alioth' }] });
    // 4)类型查询("$exists"条件判定)
    ctx.model.User.find({ name: { $exists: true } }, function (error, docs) {
      //返回表中所有存在name属性的结果
    });
    ctx.model.User.find({ name: { $exists: false } }, function (error, docs) {
      //返回表中所有不存在name属性的结果
    });
    // 5)匹配正则表达式查询
    // MongoDb 使用 Prel兼容的正则表达式库来匹配正则表达式
    ctx.model.User.find({ name: /Alioth/i }); // 返回表中name为 Alioth 的结果, 并忽略大小写
    // 6)查询数组
    ctx.model.User.find({ array: 10 }); // 返回表中array(数组类型)键中有10的文档, array : [1,2,3,4,5,10] 会匹配到
    ctx.model.User.find({ 'array[5]': 10 }); // 返回表中array(数组类型)键中下标5对应的值是10, array : [1,2,3,4,5,10] 会匹配到
    ctx.model.User.find({ array: [5, 10] }); // 返回表中查询匹配array数组中既有5又有10的结果
    ctx.model.User.find({ array: { $size: 3 } }); // 返回表中查询匹配array数组长度为3 的的结果
    ctx.model.User.find({ array: { $slice: 10 } }); // 返回表中查询匹配array数组的前10个元素
    ctx.model.User.find({ array: { $slice: [5, 10] } }); // 返回表中查询匹配array数组的第5个到第10个元素
    // 7)where
    // 用它可以执行任意javacript语句作为查询的一部分,如果回调函数返回 true 文档就作为结果的一部分返回
    // 其中this为数据表中的数据,上述返回表中属性x+属性y=10的所有数据
    ctx.model.User.find({ $where: 'this.x + this.y === 10' });
    ctx.model.User.find({ $where: 'function(){ return this.x + this.y ===10; }' })


    /** 三 删除数据 */
    // 备注:conditions为查询条件,与查询数据介绍的一样,eg:{ _id:'5ba05c89b1f3b6355e1d635e' },找到_id为5ba05c89b1f3b6355e1d635e的数据,callback为操作成功后的回调函数
    ctx.model.User.remove(conditions, callback);


    /** 四 更新数据 */
    // 参数1:查询条件, 参数2:更新对象,可以使用MondoDB的更新修改器
    // 备注:conditions与查询数据中介绍的一样
    ctx.model.User.update(conditions, update, callback);

    // 1.update为更新对象
    // 查询表中特定_id,并对data中所包含的属性进行更新。
    let data = { name: 'Jodie' }
    ctx.model.User.update({ _id: '5ba05c89b1f3b6355e1d635e' }, data)

    // 2.update使用MondoDB的更新修改器,有以下几种使用场景
    // 1)"$inc"增减修改器,只对数字有效
    // 找到age=22的文档,修改文档的age值自增1
    ctx.model.User.update({ "age": 22 }, { $inc: { "age": 1 } });
    // 2)'$set' 指定一个键的值,这个键不存在就创建它.可以是任何MondoDB支持的类型.
    // 对5c4a819fb87ba4002a47bc4f 表进行软删除,找到特定_id数据,增加或者修改isDelete属性
    ctx.model.User.update({ _id: '5ba05c89b1f3b6355e1d635e' }, { $set: { isDelete: true } });
    // 3)"$unset"同上取反,删除一个键
    // 执行后create_at键不存在
    ctx.model.User.update({ create_at: new Date(2019, 7, 5) }, { $unset: { create_at: '' } });
    // 4)'$push'给一个键push一个数组成员,键不存在会创建,对数组有效
    // 返回表中name为Jodie的数据,增加一个array键,类型为数组,有一个成员 10
    ctx.model.User.update({ name: 'Jodie' }, { $push: { array: 10 } });
    // 5)'$addToSet'向数组中添加一个元素,如果存在就不添加
    // 返回表中name为Jodie的数据,array中有10所以不会添加
    ctx.model.User.update({ name: 'Jodie' }, { $addToSet: { array: 10 } });
    // 6)'$each'遍历数组和 $push 修改器配合可以插入多个值
    // 返回表中name为Jodie的数据,执行后array : [10,1,2,3,4,5]
    ctx.model.User.update({ name: 'Jodie' }, { $push: { array: { $each: [1, 2, 3, 4, 5] } } });
    // 7)'$pop' 向数组中尾部删除一个元素
    // 返回表中name为Jodie的数据,其中array : [10,1,2,3,4,5],执行后 array : [10,1,2,3,4]
    // tip:将1改成-1可以删除数组首部元素
    ctx.model.User.update({ name: 'Jodie' }, { $pop: { array: 1 } });
    // 8)'$pull' 向数组中删除指定元素
    // 返回表中name为Jodie的数据,匹配到array中的10后将其删除。
    ctx.model.User.update({ name: 'Jodie' }, { $pull: { array: 10 } });


    /** 五 排序(sort) */
    // 对表中的数据进行排序,先按'isSetTop'降序,再按'sort'升序,最后按'editTime'降序
    // 备注:键对应数据中的键名,值代表排序方向,1升序, -1降序。
    ctx.model.User.sort({ isSetTop: -1, sort: 1, editTime: -1 });


    /** 六 限制返回结果的数量(limit) */
    // 对表中的数据进行返回,返回为前面3条数据
    ctx.model.User.limit(3);


    /** 七 跳过前3个文档,返回其余的(skip)) */
    // 对表中的数据进行返回,跳过前面3条数据,返回其余数据
    ctx.model.User.skip(3);

    // 附:综合使用最后三个方法进行分页查询
    // 其中pageSize和pageNum为动态传递数据,返回Article表中特定_id在每页数据为pageSize条件下的第pageNum页中的数据,并按照“isSetTop”降序,再按“sort”升序,最后按“editTime”降序进行排序。
    ctx.model.User.find({ _id: '5ba05c89b1f3b6355e1d635e' }).skip(pageSize * (pageNum - 1)).limit(parseInt(pageSize)).sort({ isSetTop: -1, sort: 1, editTime: -1 });
  }
}
module.exports = GluiController;