连接数据库
在egg.js中使用mongoose
1.egg.js官网只推荐了mysqle,要用mongodb得另找资料。通过查找,大家都在用Mongoose连接,于是乎学习**。**
网站链接:https://www.npmjs.com/package/egg-mongoose
使用方法: https://mongoosejs.com/docs/guide.html
2.第一步:安装
npm i egg-mongoose --save
3.配置
安装完成之后在目录/config/plugin.js中引用
// config/plugin.js
exports.exports = {
mongoose: {
enable: true,
package: "egg-mongoose",
},
};
在/config/config.default.js中加入配置
// config/config.default.js
// 数据库配置
exports.mongoose = {
client: {
url: 'mongodb://127.0.0.1:27017/databaseName', // 你的数据库地址,databaseName是你数据库得名字
options: {},
},
};
4.使用
01- 搞个model(领域模型)文件夹 设计数据库表的格式
例子:
在app下新建文件夹model,model下新建article.js文件,完整路径app/model/article.js
// app/model/article.js
'use strict'; // 可选严格模式
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
// 下面得操作是连接数据库
const ArticleSchema = new Schema({
// 修改和新增用到,规定字段得类型和其他条件等
title: {
type: String,
required: true,
},
summary: {
type: String,
},
}, { versionKey: false });
// 自己创建条数据 没有数据去创建数据
// mongoose.model('Article', ArticleSchema, 'article').create({
// title: "第一条",
// summary: "你好 mongdb",
// });
return mongoose.model('Article', ArticleSchema, 'article'); // Article是指定查找的入口,随便取;ArticleSchema是参数;article是你数据集合表的名称
};
02- service (务逻辑层)
这里编写逻辑(对数据库的: 增删改查)
// app/service/article.js
'use strict';
const Service = require('egg').Service;
class ArticleService extends Service {
/**
* 根据ID获取单个项目
*/
async getProjectById() {
const { ctx, app } = this;
try {
// 查询表 model.Article.find
const results = await ctx.model.Article.find({ // Article为modal/article.js里面命名的名字
// id为: xxx
_id: app.mongoose.Types.ObjectId('5da034149b6e823ca2ea809d'),
});
return results;
} catch (err) {
ctx.body = JSON.stringify(err);
}
}
}
module.exports = ArticleService;
03- 控制器 编写api的入口
这在之前的课件中介绍过了
// 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;
04- 配置路由
具体在之前的课程中有介绍
// 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);
};
t(’/’, controller.home.index);
router.get(’/article’, controller.article.index);
};