egg数据库操作(增删改查)

1.数据库的增加(单个和多个)

对于上述数据库的迁移我们进行了阐述,今天我们开始对数据库操作进行学习。我们会详尽增删改查的操作,开始我们的正题吧。首先创建我们的模型文件:app/model/user.js

然后书写数据库部分:

// app / model / user.js

'use strict';
module.exports = app => {
  const { STRING, INTEGER, DATE , ENUM} = app.Sequelize;
  // 配置(重要:一定要配置详细,一定要!!!)
  const User = app.model.define('user', {
    id: { type: INTEGER(20).UNSIGNED, primaryKey: true, autoIncrement: true },
      username: { type: STRING(30), allowNull: false, defaultValue: '', comment: '用户名称', unique: true},
      password: { type: STRING(200), allowNull: false, defaultValue: '' },
      avatar_url: { type: STRING(200), allowNull: true, defaultValue: '' },
      sex: { type: ENUM, values: ['男','女','保密'], allowNull: true, defaultValue: '男', comment: '用户性别'},
      created_at: DATE,
      updated_at: DATE
  },{
    timestamps: true, // 是否自动写入时间戳
    tableName: 'user', // 自定义数据表名称
 });

  return User;
};

这个 Model 就可以在 Controller 和 Service 中通过 app.model.User 或者 ctx.model.User 访问到了,例如我们编写 app/controller/user.js :这里我先写死数据,进行新增动作

  // 创建用户
  async create() {
    const { ctx } = this;


    // 写入数据库
    let res = await this.app.model.User.create({
        username:"测试",
        password:'123456',
        sex:"男"
    });

    ctx.body = res;
    
  }

批量新增的操作:新增多个

 async create() {
    const { ctx } = this;
    //批量新增数据库
    let res = await this.app.model.User.bulkCreate([
        {
            username:"测试1",
            password:'123456',
            sex:"男"
        },
        {
            username:"测试2",
            password:'123456',
            sex:"女"
        }
    ]); 
    ctx.body = res;

  }

然后执行后的结果如下:

2.数据库的查询:(单个和多个)

根据用户传递过来的id,来进行查询:

  //读取用户数据
  async read() {
    const { ctx } = this;

    //读取传递的参数
    let id = parseInt(this.ctx.params.id);

    //通过主键查询单个数据
    let res = await this.app.model.User.findByPk(id);

    ctx.body = {
      msg: "ok",
      data: res,
    };

  }

也可以通过where的条件查询:

  //读取用户数据
  async read() {
    const { ctx } = this;

    //读取传递的参数
    let id = parseInt(this.ctx.params.id);
    //根据条件查询
    let res = await this.app.model.User.findOne({
        where:{
            id
        }
    });
    ctx.body = {
      msg: "ok",
      data: res,
    };
  }

findAll:查询多个数据。findAndCountAll:查询多个并计数

如下:我们增加了where条件,对只有男的才查询,结果如下

async index() {
    const { ctx } = this;
    //查询列表数据
    let result = [];

    // 查询多个
    result =  await this.app.model.User.findAll({
       where:{
           sex:'男'
       }
    });
    //拿到数据
    ctx.body = {
      msg: "ok",
      data: result,
    };
    this.ctx.status = 200;
  }

也可以进行模糊查询:这里需要注意的是op对象。其实对于这个,还是要很多操作可以书写的。

  async index() {
    const { ctx } = this;
    //查询列表数据
    let result = [];

    // 查询多个 
    let Op = this.app.Sequelize.Op;  //获取op对象
    result =  await this.app.model.User.findAll({
       where:{
           sex:'男',
           username:{
              [Op.like]:"%1%" 
           }
       }
    });
    //拿到数据
    ctx.body = {
      msg: "ok",
      data: result,
    };
    this.ctx.status = 200;
  }

op对象的一些操作:

const Op = Sequelize.Op

[Op.and]: {a: 5}           // 且 (a = 5)
[Op.or]: [{a: 5}, {a: 6}]  // (a = 5 或 a = 6)
[Op.gt]: 6,                // id > 6
[Op.gte]: 6,               // id >= 6
[Op.lt]: 10,               // id < 10
[Op.lte]: 10,              // id <= 10
[Op.ne]: 20,               // id != 20
[Op.eq]: 3,                // = 3
[Op.not]: true,            // 不是 TRUE
[Op.between]: [6, 10],     // 在 6 和 10 之间
[Op.notBetween]: [11, 15], // 不在 11 和 15 之间
[Op.in]: [1, 2],           // 在 [1, 2] 之中
[Op.notIn]: [1, 2],        // 不在 [1, 2] 之中
[Op.like]: '%hat',         // 包含 '%hat'
[Op.notLike]: '%hat'       // 不包含 '%hat'
[Op.iLike]: '%hat'         // 包含 '%hat' (不区分大小写)  (仅限 PG)
[Op.notILike]: '%hat'      // 不包含 '%hat'  (仅限 PG)
[Op.startsWith]: 'hat'     // 类似 'hat%'
[Op.endsWith]: 'hat'       // 类似 '%hat'
[Op.substring]: 'hat'      // 类似 '%hat%'
[Op.regexp]: '^[h|a|t]'    // 匹配正则表达式/~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.notRegexp]: '^[h|a|t]' // 不匹配正则表达式/!~ '^[h|a|t]' (仅限 MySQL/PG)
[Op.iRegexp]: '^[h|a|t]'    // ~* '^[h|a|t]' (仅限 PG)
[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (仅限 PG)
[Op.like]: { [Op.any]: ['cat', 'hat']} // 包含任何数组['cat', 'hat'] - 同样适用于 iLike 和 notLike
[Op.overlap]: [1, 2]       // && [1, 2] (PG数组重叠运算符)
[Op.contains]: [1, 2]      // @> [1, 2] (PG数组包含运算符)
[Op.contained]: [1, 2]     // <@ [1, 2] (PG数组包含于运算符)
[Op.any]: [2,3]            // 任何数组[2, 3]::INTEGER (仅限PG)

[Op.col]: 'user.organization_id' // = 'user'.'organization_id', 使用数据库语言特定的列标识符, 本例使用 PG

当我们查询部分字段的值的时候,我们可以使用:attributes,来对字段筛选。order字段:来进行排序,

  async index() {
    const { ctx } = this;
    //查询列表数据
    let result = [];

    // 查询多个 
    let Op = this.app.Sequelize.Op;  //获取op对象
    result =  await this.app.model.User.findAll({
       where:{
           sex:'男'
       },
       attributes:['id','username','sex'],
       order:[
           ['id','desc']
       ]
    });
    //拿到数据
    ctx.body = {
      msg: "ok",
      data: result,
    };
    this.ctx.status = 200;
  }

3.删除数据

async destroy(){

    let id =this.ctx.params.id ? parseInt(this.ctx.params.id):0;

    //查询出来数据
    let res = await this.app.model.User.destroy({
        where:{
            id
        }
    });

    this.ctx.body={
        msg:'ok',
        data:res
    }
  }

结果如下:第四条数据已经被删除

如果是批量删除,就可以在where内部传递条件来进行操作。

上述讲述的都是非常简单的操作,后续我会结合部分项目来进行更详细的介绍。

 

  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
对于基本的增删改查操作,使用mongoose可以按照以下步骤进行: 1. 定义数据模式Schema:在定义数据模式时使用mongoose.Schema来创建一个新的模式对象。可以通过指定字段名称和类型来定义模式的属性,例如: ```javascript const mongoose = require("mongoose"); const Schema = mongoose.Schema; const NewsSchema = new Schema({ name: {type: String}, age: {type: Number}, sex: {type: String, required: [true, '请选择性别']} }); ``` 2. 定义数据模型Model:通过mongoose.model来创建一个新的模型对象,参数1为模型的名称,参数2为使用的模式对象,参数3为集合名称。例如: ```javascript const UserModel = mongoose.model('User', NewsSchema, 'user'); ``` 3. 增加数据:使用模型对象的create方法来创建一个新的文档,并将其保存到数据库中。例如: ```javascript UserModel.create({name: 'John', age: 25, sex: 'Male'}, (err, doc) => { if(err) { console.log(err); } else { console.log(doc); } }); ``` 4. 查询数据:使用模型对象的find方法来查询符合条件的文档。例如: ```javascript UserModel.find({name: 'John'}, (err, docs) => { if(err) { console.log(err); } else { console.log(docs); } }); ``` 5. 更新数据:使用模型对象的updateOne或updateMany方法来更新符合条件的文档。例如: ```javascript UserModel.updateOne({name: 'John'}, {age: 30}, (err, result) => { if (err) { console.log(err); } else { console.log(result); } }); ``` 6. 删除数据:使用模型对象的deleteOne或deleteMany方法来删除符合条件的文档。例如: ```javascript UserModel.deleteOne({name: 'John'}, (err) => { if (err) { console.log(err); } else { console.log('删除成功'); } }); ``` 以上是使用mongoose进行基本增删改查的步骤。可以根据具体的需求和条件进行相应的操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [mongoose实现增删改查](https://blog.csdn.net/qq_44747461/article/details/121178662)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* [eggjs实战(5)——eggjs+mongoose(egg-mongoose)增删改查技巧](https://blog.csdn.net/zjsj_lize/article/details/120938407)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值