Directory
- Installation
- Project
- Connecting to a database
- Writing model
- Writing a Controller
- Add route
2018-08, this article applies to the students who are interested in learning about egg
Complete Project code: Https://github.com/NameHewei/node-egg
Project main file directory structure
|—— app |—— controller |—— cook.js |—— model |—— cook.js |—— router.js|—— config |—— config.default.js |—— plugin.js|—— package.json|—— README.md
Installation
Official website: https://eggjs.org/zh-cn/
- NPM I Egg-init-g
- Egg-init Egg-example--type=simple
- CD Egg-example
- NPM I
Start Project
Project
This article is mainly to build a backend to connect MongoDB to provide API interface
Connecting to a database
- Introduce the database plug-in and add the following code to the Plugin.js file
exports.mongoose = { enable: true, package: ‘egg-mongoose‘,};
- Add the following configuration in Config.default.js
config.mongoose = { client: { url: ‘mongodb://127.0.0.1:27017/database-name‘, },}
Writing model
Added under Model file, Cook.js file
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);}
Note If you use _id in MongoDB type, and how to remove the __v version lock field.
Writing a Controller
Add the Cook.js file under the Controller folder
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;
This is used to get the data in the database
Add route
module.exports = app => { const { router, controller } = app; router.get(‘/cook/‘, controller.cook.list); router.get(‘/cook/:id‘, controller.cook.listOne);};
After you have made sure that the database is connected successfully, you can start the project.
This article is only to assist in the rapid construction of a basic egg project, the specific content please refer to: https://eggjs.org/
If you have any questions or errors, please leave a message, thank you! Github Blog Issues
Egg Self-taught introduction demo sharing