egg-mongoose --- nodejs


項目

egg + mongoose


 

項目結構

 

配置


 

egg 安裝模塊

npm i egg-mongoose --save

 

config/pulgin.js

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

 

config/config.default.js

exports.mongoose = {
    url: 'mongodb://127.0.0.1/demo',
    //鏈接到本地的MongoDB,demo是我本地數據庫的名字,根據自己數據庫名字進行填寫即可
    options: {},
};

 

數據建模


 

model/user.js

// 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, 'userInfo');
    // model(參數1,參數2,參數3)參數3是你數據表中需要操作的表的名字,
    // 比如我現在要操作的是名字叫mongoTest里面的叫userInfo的表
}

 

 

service


 service/user.js

'use strict';
// app/service/user.js
const Service = require('egg').Service;

class UserService extends Service {
  async findUserList() {
    return this.ctx.model.User.find()
  }
}
module.exports = UserService;

 

controller


 controller/user.js

'use strict';

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

class UserController extends Controller {
  async findUser() {
    // console.log(this.ctx.service.user.findUserList())
    // let ret = await this.ctx.service.user.findUserList()
    // this.ctx.body = ret

    this.ctx.body = await this.ctx.service.user.findUserList()

  }
}

module.exports = UserController;

 

router.js


 

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/findUser', controller.user.findUser);
};

 

 

查詢結果


 

 


免責聲明!

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



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