配置mongoose连接时,报错对象未定义Cannot read property 'Bank' of undefined
请使用 npm init egg --type=simple bug 创建,并上传到你的 GitHub 仓库
https://github.com/shinji3887/eggjs-demo
controller代码:
'use strict';
const Controller = require('egg').Controller;
class BankController extends Controller {
async index() {
const { ctx } = this;
//ctx.response.body = {ret:'121212'}
ctx.body = await this.model.Bank.find({});
}
}
module.exports = BankController;
model代码:
'use strict';
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: { type: String },
age: { type: Number },
company: { type: String}
});
return mongoose.model('Bank', UserSchema,'col');
}
plugin配置:
'use strict';
/** @type Egg.EggPlugin */
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
};
exports.mongoose = {
enable: true,
package: 'egg-mongoose'
};
config.default.js配置:
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1581178232166_9983';
// add your middleware config here
config.middleware = ['auth'];
config.mongoose = {
client: {
url: 'mongodb://127.0.0.1/eggcms',
options: {}
},
};
// add your user config here
const userConfig = {
// myAppName: 'egg',
auth: {
threshold: 1033, // 小于 1k 的响应体不压缩
enable: true
}
};
return {
...config,
...userConfig,
};
};
错误日志:
2020-02-10 00:14:19,867 ERROR 23485 [-/127.0.0.1/-/19ms GET /users?id=admin] nodejs.TypeError: Cannot read property 'Bank' of undefined at BankController.index (/Users/keyibunn/eggjs/app/controller/bank.js:10:33) at Object.callFn (/Users/keyibunn/eggjs/node_modules/egg-core/lib/utils/index.js:44:21) at Object.classControllerMiddleware (/Users/keyibunn/eggjs/node_modules/egg-core/lib/loader/mixin/controller.js:87:20) at Object.callFn (/Users/keyibunn/eggjs/node_modules/@eggjs/router/lib/utils.js:12:21) at wrappedController (/Users/keyibunn/eggjs/node_modules/@eggjs/router/lib/egg_router.js:322:18) at dispatch (/Users/keyibunn/eggjs/node_modules/koa-compose/index.js:44:32) at next (/Users/keyibunn/eggjs/node_modules/koa-compose/index.js:45:18) at /Users/keyibunn/eggjs/node_modules/@eggjs/router/lib/router.js:190:18 at dispatch (/Users/keyibunn/eggjs/node_modules/koa-compose/index.js:44:32) at /Users/keyibunn/eggjs/node_modules/koa-compose/index.js:36:12