天天看点

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 } },
      },
 ]);