搭建eggjs环境
npm init egg --type=simple- simple简单 egg 应用程序骨架
- empty空的 egg 应用程序骨架
- plugin egg plugin 骨架
- framework egg framework 骨架
npm i & npm run dev
本demo项目结构
目录结构详解: https://www.eggjs.org/zh-CN/basic…
连接mongoose
- 安装依赖
npm i egg-mongoose --save
- 配置
./config/config.default.js./config/pulugin.js
// config.default.js
// ...
const config = (exports = {
security: {
// 关闭csrf安全机制(有条件的不要关闭,这里是为了测试接口,不关闭的话postman测试时的post请求会报错)
csrf: false,
},
mongoose: {
client: {
// 数据库地址
// url: "mongodb://eggadmin:123456@localhost:27017/my_todolist", //有用户名密码的情况
url: "mongodb://127.0.0.1/my_todolist", // 没有用户名密码情况
options: {
},
},
},
// 多个数据库的时候
// clients: {
// // db1 数据库别名
// db1: {
// url: "mongodb:127.0.0.1/user",
// options: {},
// },
// db2: {
// url: "mongodb:127.0.0.1/good",
// options: {},
// },
// },
});
// ...
// ./config/pulugin.js`
"use strict";
/** @type Egg.EggPlugin */
module.exports = {
// had enabled by egg
static: {
enable: true,
},
mongoose: {
enable: true,
// 使用插件
package: "egg-mongoose",
},
};
简单的crud
为了方便,Egg 在this上绑定了以下对象
- this.ctx:当前请求的上下文 Context 对象的实例,通过它我们可以拿到框架封装好的处理当前请求的各种便捷属性和方法
- this.app:当前应用 Application 对象的实例,通过它我们可以拿到框架提供的全局对象和方法
- this.service:应用定义的 Service,通过它我们可以访问到其他业务层,等价于 this.ctx.service
- this.config:应用运行时的配置项
- this.logger:logger 对象,上面有四个方法(debug,info,warn,error),分别代表打印四个不同级别的日志,通过这个 logger 对象记录的日志,在日志前面会加上打印该日志的文件路径,以便快速定位日志打印位置
// app>controller>list.js
"use strict";
const { Controller } = require("egg");
class HomeController extends Controller {
async get() {
const { ctx } = this;
let res = await this.service.list.getlist();
ctx.body = {
code: 200,
data: {
list: res,
},
};
}
async add() {
const { ctx } = this;
let res = await this.service.list.addlist();
ctx.body = {
code: 200,
data: {
msg: "添加成功",
},
};
}
async del() {
const { ctx } = this;
let res = await this.service.list.dellist();
ctx.body = {
data: {
code: 200,
msg: res,
},
};
}
async upd() {
const { ctx } = this;
let res = await this.service.list.updlist();
ctx.body = {
data: {
code: 200,
msg: res,
},
};
}
}
module.exports = HomeController;
// app>model>list.js
module.exports = (app) => {
const mongoose = app.mongoose;
// const conn = app.mongooseDB.get("db1"); //多个数据库的时候
const listSchema = new mongoose.Schema({
name: {
type: String,
default: "",
},
});
return mongoose.model("List", listSchema, "list");
// return conn.model("List", listSchema, "list"); // //多个数据库的时候
};
Service 文件必须放在 app/service 目录,可以支持多级目录,访问的时候可以通过目录名级联访问
- app/service/demo/user.js => ctx.service.demo.user
- app/service/sync_user.js => ctx.service.syncUser
- ...
// app>service>list.js
"use strict";
const Service = require("egg").Service;
class ListService extends Service {
async getlist() {
const { ctx } = this;
const res = await ctx.model.List.find();
return res;
}
async addlist() {
const { ctx } = this;
const res = await ctx.model.List.create(ctx.request.body);
return res;
}
async dellist() {
const { ctx } = this;
const { id } = ctx.request.body;
let res;
if (id) {
await ctx.model.List.deleteOne({ _id: id });
res = "删除成功"
} else {
res = "id不存在";
}
return res;
}
async updlist() {
const { ctx } = this;
const {id} = ctx.request.body;
await ctx.model.List.updateOne({ _id: id }, ctx.request.body);
return "更新成功"
}
}
module.exports = ListService;
// app>router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/get', controller.list.get);
router.post('/add', controller.list.add);
router.post('/del', controller.list.del);
router.post('/upd', controller.list.upd);
};