Egg使用MongoDB时运行出现:TypeError:Cannot read property ‘hasOwnProperty‘ of undefined

各种排查查阅,最终发现是由于我的MongoDB中的egg_test数据库并没有给它设置相应的管理员账号所致,= =|||

  1. 进入MongoDB
  2. 切换数据库:use egg_test
  3. 创建用户:db.createUser({user: “root”, pwd: “root”, roles: [{ role: “dbOwner”, db: “test” }]})
  4. 查看用户:show users
  5. 搞定啦~
  6. 【注意】配置文件里要按下面的来配哦

在Egg中安装MongoDB

VS Code命令行中输入:npm i egg-mongoose --save

配置

文件目录:/config/plugin.js
exports.mongoose = {
enable: true,
package: ‘egg-mongoose’,
};

文件目录:/config/config.default.js
config.mongoose = {
client: {
url: ‘mongodb://127.0.0.1’,
options: {
user: ‘root’,
pass: ‘root’,
dbName: ‘egg_test’,
},
},
};

在app下新建文件夹model,model下新建tea.js文件

‘use strict’;

module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const TeaSchema = new Schema({
name: {type: ‘string’},
password: {type: ‘string’},
});
return mongoose.model(‘Tea’, TeaSchema’);

};

在app下新建文件夹service,service下新建tea.js文件

‘use strict’;

const Service = require(‘egg’).Service;

class TeaService extends Service {
async getTeaByName() {
const ctx = this;
try {
const results = await ctx.model.Tea.find({
name: ‘jack’,
});
return results;
} catch (err) {
ctx.body = JSON.stringify(err);
}
}

}
module.exports = TeaService ;

在app下controller文件夹新建tea.js

‘use strict’;
const Controller = require(‘egg’).Controller;

class TeaController extends Controller {
async index() {
const { ctx } = this;
const result = await ctx.service.tea.getTeaByName();
ctx.body = result ;
}
}

module.exports = TeaController ;

配置路由

‘use strict’;

/**

  • @param {Egg.Application} app - egg application
    */
    module.exports = app => {
    const { router, controller } = app;
    router.get(’/’, controller.home.index);
    router.get(’/tea’, controller.tea.index);
    };
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值