egg 自學入門demo分享


2018-08,本文適用於對egg有興趣想要了解的同學

完整項目代碼:https://github.com/NameHewei/node-egg

項目主要文件目錄結構

|—— app
    |—— controller
        |—— cook.js
    |—— model
        |—— cook.js
    |—— router.js
|—— config
    |—— config.default.js
    |—— plugin.js
|—— package.json
|—— README.md

安裝

官網: https://eggjs.org/zh-cn/

  1. npm i egg-init -g
  2. egg-init egg-example --type=simple
  3. cd egg-example
  4. npm i

啟動項目

  • npm run dev

項目

本文主要是以搭建一個連接mongoDB的后端,以提供api接口

連接數據庫

  1. 引入數據庫插件,在plugin.js文件中添加如下代碼
exports.mongoose = {
    enable: true,
    package: 'egg-mongoose',
};
  1. 在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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM