Egg 中使用 Mongoose 以及 Egg 中的 model

一、Egg 中的 model
app/model/** 用于放置领域模型,可选,由领域类相关插件约定。

Loader : Egg Koa 的基础上进行增强最重要的就是基于一定的约定,根据功能差异将代码 放到不同的目录下管理,对整体团队的开发成本提升有着明显的效果。Loader 实现了这套 约定,并抽象了很多底层 API 可以进一步扩展。

Loader 还提供了 caseStyle 强制指定首字母大小写,比如加载 model API 首字母大写, app/model/user.js => app.model.User

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

二、Egg 中使用 Mongoose

1、在 egg 项目中安装 mongoose

npm i egg-mongoose --save

2、在 {app_root}/config/plugin.js 中启用 egg-mongoose 插件:

exports.mongoose = { 
enable: true,
package: 'egg-mongoose',
};

3、在配置文件中配置 mongoose 数据库连接地址 {app_root}/config/config.default.js

//第一种配置方式 
exports.mongoose = {
    url: 'mongodb://127.0.0.1/example',
    options: {}, 
};
//第二种推荐配置方式 
exports.mongoose = {
  client: {
      url: 'mongodb://127.0.0.1/example', 
      options: {},
  }, 
};

4、在 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); }

5、在 egg 项目控制器或者服务里面使用 mongoose

// {app_root}/app/controller/user.js
exports.index = function* (ctx) {
    ctx.body = await ctx.model.User.find({});
}

demo :

/app/model/user.js
module.exports = app => {

    const mongoose = app.mongoose;   /*引入建立连接的mongoose */
    const Schema = mongoose.Schema;
   

    //数据库表的映射
    const UserSchema = new Schema({
      username: { type: String  },
      password: { type: String  },
      status:{
        type:Number,
        default:1
      }

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

controller/user.js

'use strict';

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

class UserController extends Controller {
  async index() {



    var userList=await this.service.user.getUserList();
    console.log(userList);       
  

    this.ctx.body='我是用户页面';
    
  }

  async addUser() {
    //增加数据

    var user=new this.ctx.model.User({
        username:'李四',
        password:'123456'

    });

    var result=await user.save();
    console.log(result)



    this.ctx.body='增加用户成功';
    
  }

  async editUser() {
    //增加数据


    await this.ctx.model.User.updateOne({
        "_id":"5b84d4405f66f20370dd53de"
    },{
      username:"哈哈哈",
      password:'1234'
    },function(err,result){

      if(err){
        console.log(err);
        return;
      }
      console.log(result)
    })

    this.ctx.body='修改用户成功';
    
  }

  async removeUser() {
    //增加数据

    var rel =await this.ctx.model.User.deleteOne({"_id":"5b84d4b3c782f441c45d8bab"});

    cnsole.log(rel);

    this.ctx.body='删除用户成功';
    
  }
}

module.exports = UserController;
原文地址:https://www.cnblogs.com/loaderman/p/11570921.html