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;

 

 


免責聲明!

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



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