node egg connects to the database egg-sequelize-plus

1. Installation

npm install egg-sequelize-plus --save

2. Modify the configuration in config/config.default.js


module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {
    // 从这开始为连接数据库的配置
    sequelizePlus: {
      dialect: 'mysql', // support: mysql, mariadb, postgres, mssql 
      database: '****', // 数据库名称
      host: '***.***.***.***', // 服务器IP地址
      port: 3306, // 数据库端口一般都是3306
      username: '******', // 用户名
      password: '******', // 密码
      logging: false,
      options: {
        timezone: 'Asia/Shanghai',
        pool: {
          maxConnections: 5,
        },
      },
    },
    // 到这里结束
  };

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1648170127232_8593';

  // add your middleware config here
  config.middleware = [];

  // add your user config here
  const userConfig = {
    // myAppName: 'egg',
  };

  return {
    ...config,
    ...userConfig,
  };
};

3. Modify config/plugin.js

Seeing that other articles are not placed in static, I tried to report an error:

Cannot use 'in' operator to search for 'enable' in egg-sequelize-plus

Just put it in there.

'use strict';

/** @type Egg.EggPlugin */
module.exports = {
  // had enabled by egg
  static: {
    enable: true,
    package: 'egg-sequelize-plus',
  },

};

4. Define the model


module.exports = app => {
    const { STRING, INTEGER, DATE } = app.Sequelize;
    const User = app.model.define('user', {
        login: STRING,
        name: STRING(30),
        password: STRING(32),
        age: INTEGER,
        last_sign_in_at: DATE,
        created_at: DATE,
        updated_at: DATE,
    });
    User.findByLogin = async function (login) {
        return await this.findOne({
            where: {
                login: login
            }
        });
    }
    // don't use arraw function  
    User.prototype.logSignin = async function () {
        return await this.update({
            last_sign_in_at: new Date()
        });
    }

    // User.sync({ force: true });  //同步数据库,开发开始时同步一次就好了,不然每次修改更新后都会清空数据库内容
    return User;
}; 

5. Simple example of CRUD

const Controller = require('egg').Controller;

class UserController extends Controller {
    async index() {
        console.log(this.ctx.query);
        const users = await this.ctx.model.User.findAll();
        this.ctx.body = users;
    }

    async add() {
        await this.ctx.model.User.create(this.ctx.request.body);
        this.ctx.body = {
            code: 200,
        }
    }

    async update() {
        await this.ctx.model.User.update(this.ctx.request.body, {
            where: {
                id: this.ctx.request.body.id
            }
        });
        this.ctx.body = {
            code: 200,
        }
    }

    async delete() {
        await this.ctx.model.User.destroy({
            where: {
                id: this.ctx.query.id,
            }
        });
        this.ctx.body = {
            code: 200,
        }
    }
}

module.exports = UserController;

You can request by adding a routing interface before.

If you are interested, you can follow me, and I will continue to update in the future.

Guess you like

Origin blog.csdn.net/qq_18676843/article/details/123730685