eggjs连接数据库

发布时间 2023-06-29 19:37:44作者: 走走停停走走

 

 

创建项目之后, 我们就开始配置怎么通过egg-mysql连接并操作mysql数据库啦

安装egg-mysql插件
cnpm i -S egg-mysql
开启插件

config/plugin.js

module.exports = {
  mysql: {
    enable: true,
    package: 'egg-mysql'
  }
};
配置数据库连接信息

可以配置单数据源也可以配置多数据源, 下面我们这里只讲配置但数据源
在/config/config.default.js中增加数据库配置

'use strict';

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {
    // 数据库配置
    mysql: {
      // 单数据库信息配置
      client: {
        // host
        host: 'ip地址',
        // 端口号
        port: '3306',
        // 用户名
        user: 'root',
        // 密码
        password: '123456',
        // 数据库名
        database: 'test',
      },
      // 是否加载到 app 上,默认开启
      app: true,
      // 是否加载到 agent 上,默认关闭
      agent: false,
    }
  };

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

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

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

  return {
    ...config,
    ...userConfig,
  };
};
编写Service层代码

这这里我们通过刚才配置的mysql直接和数据库交互
app/service/user.js

'use strict';

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

class UserService extends Service {
  async getUserById(id) {
    // 根据id查询用户信息
    return await this.app.mysql.get('users', {id: id});
  }
}
module.exports = UserService;

编写Controller层代码

在这里, 我们调用Service层的代码间接和数据库交互
app/controller/user.js

'use strict';

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

class UserController extends Controller {
  async index() {
    // 根据id查询用户信息
    let users = await this.ctx.service.user.getUserById(2);
    this.ctx.body = users;
  }
}
module.exports = UserController;
最好编写我们的路由规则

app/router.js

module.exports = app => {
  const { router, controller } = app;
  // http://127.0.0.1:7001/user 会映射到app/controller/user.js 的index方法上
  router.get('/user', controller.user.index);
};

到这里我们就写完了, 一起测试一把吧
访问: http://127.0.0.1:7001/user

{"id":2,"name":"测试2","age":11,"created_at":"2019-07-10T03:49:11.000Z","updated_at":"2019-07-24T03:49:14.000Z"}


作者:iDevOps
链接:https://www.jianshu.com/p/6a6f80adcb06
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。