2018-08,本文適用於對egg有興趣想要了解的同學
項目主要文件目錄結構
|—— app
|—— controller
|—— cook.js
|—— model
|—— cook.js
|—— router.js
|—— config
|—— config.default.js
|—— plugin.js
|—— package.json
|—— README.md
安裝
- npm i egg-init -g
- egg-init egg-example --type=simple
- cd egg-example
- npm i
啟動項目
- npm run dev
項目
本文主要是以搭建一個連接mongoDB的后端,以提供api接口
連接數據庫
- 引入數據庫插件,在plugin.js文件中添加如下代碼
exports.mongoose = {
enable: true,
package: 'egg-mongoose',
};
- 在config.default.js中添加如下配置
config.mongoose = {
client: {
url: 'mongodb://127.0.0.1:27017/database-name',
},
}
編寫model
在model文件下添加,cook.js 文件
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const CookeSchema = new Schema({
_id: { type: Schema.Types.ObjectId },
name: { type: String },
img: { type: String },
step: { type: String }
}, {
versionKey: false
});
return mongoose.model('cooks', CookeSchema);
}
注意如果使用mongoDB中的_id時type的類型,以及如何去掉__v 版本鎖字段。
編寫controller
在controller文件夾下添加,cook.js文件
const Controller = require('egg').Controller;
class HomeController extends Controller {
async list() {
this.ctx.response.body = {
result: await this.ctx.model.Cook.find({}, {'_id': 0})
};
}
async listOne() {
const { id } = this.ctx.params
this.ctx.body = {
result: await this.ctx.model.Cook.find({ '_id': id }, {'_id': 0})
};
}
}
module.exports = HomeController;
這里用於獲取數據庫中的數據
添加路由
module.exports = app => {
const { router, controller } = app;
router.get('/cook/', controller.cook.list);
router.get('/cook/:id', controller.cook.listOne);
};
確保數據庫能連接成功后,便可以啟動項目。
本文只是輔助介紹快速搭建一個基本的egg項目,具體內容請參考:https://eggjs.org/
若有疑問或錯誤,請留言,謝謝!Github blog issues