天天看點

Egg 中使用 Mongoose 以及 Egg 中的 model

一、Egg 中的 model

app/model/** 用于放置領域模型,可選,由領域類相關插件約定。

Loader : Egg 在 Koa 的基礎上進行增強最重要的就是基于一定的約定,根據功能差異将代碼 放到不同的目錄下管理,對整體團隊的開發成本提升有着明顯的效果。Loader 實作了這約定,并抽象了很多底層 API 可以進一步擴充。

Loader 還提供了 caseStyle 強制指定首字母大小寫,比如加載 model 時 API 首字母大寫, app/model/user.js => app.model.Use

參考:https://eggjs.org/zh-cn/advanced/loader.html

二、Egg 中使用 Mongoose

1、在 egg 項目中安裝 mongoose

npm i egg-mongoose --save

2.配置

egg-mongoose

插件

打開 https://www.npmjs.com/ 搜尋egg-mongoose,按照文檔一步步配置,這裡不再贅述

3.在 egg 項目的 app 目錄裡面建立 model 檔案夾,在 model 檔案夾中定義 mongoose 的 schema 和 model。如:{app_root}/app/model/user.js

module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;

  const UserSchema = new Schema({
    username: { type: String },
    password: { type: String },
  });

  return mongoose.model('User', UserSchema);
};
           

4.在 egg 項目 service 裡面使用 mongoose

const Service = require('egg').Service;

class UserService extends Service {
  async editUser(id, password) {
    return await this.ctx.model.User.updateOne({ _id: id }, { password });
  }
}

module.exports = UserService;
           

6.最後在控制器裡調用服務

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async edit() {
    const params = [ '5d41b39d0c9ce80b60576477', 'pwd3333' ];
    const result = await this.service.user.editUser(...params);
}

module.exports = HomeController;
           

三、Egg 中使用 aggregate 實作多表查詢

const orderResult = await this.ctx.model.Order.aggregate([
      {
        $lookup: {
          from: 'order_item',
          localField: 'order_id',
          foreignField: 'order_id',
          as: 'items',
        },
      },
      {
        $match: { all_price: { $gte: 90 } },
      },
 ]);