在egg.js中使用mongodb
1.egg.js官网只推荐了mysqle,要用mongodb得另找资料。通过查找,大家都在用Mongoose连接,于是乎学习。
网站链接:https://www.npmjs.com/package/egg-mongoose
2.第一步:安装
npm i egg-mongoose --save
3.配置
安装完成之后在目录/config/plugin.js中引用
exports.mongoose = {
enable: true,
package: 'egg-mongoose',
};
在/config/config.default.js中加入
// 数据库配置
exports.mongoose = {
client: {
url: 'mongodb://127.0.0.1:27017/egg_article', // 你的数据库地址,egg_article是你数据库得名字
options: {
useNewUrlParser: true,
},
},
};


4.简单得列子
在app下新建文件夹model,model下新建article.js文件,完整路径app/model/article.js
article.js内容
'use strict';
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
// 下面得操作是连接数据库
const ArticleSchema = new Schema({
// 修改和新增用到,规定字段得类型和其他条件等
title: {
type: String,
required: true,
},
_id: {
type: Schema.ObjectId,
ref: 'Tags',
required: true,
},
summary: {
type: String,
},
}, { versionKey: false });
return mongoose.model('Article', ArticleSchema, 'article'); // 我的理解:Article是指定查找的入口,随便取;ArticleSchema是参数;article是你数据集合表的名称
};
app/service/article.js
'use strict';
const Service = require('egg').Service;
class ArticleService extends Service {
/**
* 根据ID获取单个项目
*/
async getProjectById() {
const { ctx, app } = this;
try {
const results = await ctx.model.Article.find({ // Article为modal/article.js里面命名的名字
_id: app.mongoose.Types.ObjectId('5da034149b6e823ca2ea809d'),
});
return results;
} catch (err) {
ctx.body = JSON.stringify(err);
}
}
}
module.exports = ArticleService;
app/controller/article.js
'use strict';
const Controller = require('egg').Controller;
class ArticleController extends Controller {
async index() {
const { ctx } = this;
const res = await ctx.service.article.getProjectById();
ctx.body = res; // 返回值显示
}
}
module.exports = ArticleController;
router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.get('/article', controller.article.index);
};
访问地址栏要改到/article


浙公网安备 33010602011771号