2018-08,本文适用于对egg有兴趣想要了解的同窗git
完整项目代码:https://github.com/NameHewei/node-egggithub
项目主要文件目录结构mongodb
|—— app |—— controller |—— cook.js |—— model |—— cook.js |—— router.js |—— config |—— config.default.js |—— plugin.js |—— package.json |—— README.md
官网: https://eggjs.org/zh-cn/数据库
启动项目npm
本文主要是以搭建一个链接mongoDB的后端,以提供api接口json
exports.mongoose = { enable: true, package: 'egg-mongoose', };
config.mongoose = { client: { url: 'mongodb://127.0.0.1:27017/database-name', }, }
在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 版本锁字段。api
在controller文件夹下添加,cook.js文件app
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