node egg 连接数据库 egg-sequelize-plus

1.安装

npm install egg-sequelize-plus --save

2.修改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.修改config/plugin.js

看其他文章都没有放在static里面,我试了下报错:

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

放里面就好了。

'use strict';

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

};

4.定义模型


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.增删改查的简单示例

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;

之前添加路由接口就可以请求了。

有兴趣的可以关注我,后续会持续更新。

你可能感兴趣的:(node,node.js)