egg2操作mysql报this.app.mysql.query is not a function

犯错原因,文档没看好,,,https://eggjs.org/zh-cn/basics/config.html

问题

按照官网配置mysql好后,操作数据库,报错


egg2操作mysql报this.app.mysql.query is not a function_第1张图片
TIM截图20180417172710.png

问题复现

config.default.js

exports.mysql = {
  client: {
    host: 'localhost',
    port: '3306',
    user: 'root',
    password: '123456',
    database:'nodemysql'
  },
  app: true,
  agent: false,
};

service/data.js

'use strict';
const Service = require('egg').Service;
class DataService extends Service {
  async getData() {
    const result = await this.app.mysql.select('pet');
    return {result};
  }
}
module.exports = DataService;

controller/mysql.js

'use strict';
const Controller = require('egg').Controller;
class MysqlController extends Controller {
  async index() {
    let {ctx,service} = this;
    let result = await ctx.service.data.getData();
    ctx.body=result;
  }
}
module.exports = MysqlController;

问题解决

egg2操作mysql报this.app.mysql.query is not a function_第2张图片
注意文档

通过把配置放到

'use strict';
module.exports = appInfo => {
  const config = exports = {};
  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1523879140687_7825';
  // add your config here
  config.middleware = [];
  config.mysql = {
    client: {
      host: 'localhost',
      port: '3306',
      user: 'root',
      password: 'zzzzzzz',
      database:'nodemysql'
    },
    app: true,
    agent: false,
  }
  return config;
};

你可能感兴趣的:(egg2操作mysql报this.app.mysql.query is not a function)