egg3.0使用egg-mongoose连接mongodb数据库以及查询数据

文章详细介绍了如何在Egg.js框架中安装和配置Mongoose,用于连接MongoDB数据库。首先通过npm安装egg-mongoose,然后在配置文件中设置数据库连接信息。接着,创建模型、服务和控制器来实现数据的增删查改。示例代码展示了角色(Role)模型的定义和服务中查询角色列表的方法。
摘要由CSDN通过智能技术生成

安装依赖

npm install egg-mongoose --save

package.json

  "dependencies": {
    "egg": "^3",
    "egg-mongoose": "^3.3.1",
    "egg-scripts": "^2"
  },

配置信息

config\config.default.js

'use strict';

/**
 * @param {Egg.EggAppInfo} appInfo app info
 */
module.exports = appInfo => {
  /**
   * built-in config
   * @type {Egg.EggAppConfig}
   **/
  const config = exports = {
    security: {
      csrf: {
        enable: false,
      },
    },
    mongoose: {
      client: {
      // 链接到本地的MongoDB,note是我本地数据库的名字
        url: 'mongodb://127.0.0.1:27017/note',
        options: {
          // dbName: 'note',
          useNewUrlParser: true,
        },
      },
    },
  };

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1682063943419_2410';

  // add your middleware config here
  config.middleware = [];

  // add your user config here
  const userConfig = {
    // myAppName: 'egg',
  };

  return {
    ...config,
    ...userConfig,

  };
};

config\plugin.js

'use strict';

/** @type Egg.EggPlugin */
module.exports = {
  mongoose: {
    enable: true,
    package: 'egg-mongoose',
  },
};

路由配置

app\router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/role', controller.role.index);
  router.post('/roles', controller.rolePost.index);
};

定义model

app\model\role.js

module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  // 连接数据库
  const UserSchema = new Schema({

    name: { type: String },
    id: { type: String },
  });
  // 第一个参数模型
  // 第二个参数 数据
  // 第三个参数  操作的数据集合(表)
  return mongoose.model('Role', UserSchema, 'user');

};

定义service

app\service\role.js

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

class RoleService extends Service {
  async findRoleList() {
    const { ctx } = this;
    try {
      // 説明ctx.model.Role中的Role為model目錄下文件的首字母大写
      const results = await ctx.model.Role.find();
      return results;
    } catch (err) {
      return JSON.stringify(err);
    }
  }
}
module.exports = RoleService;

定义controller

app\controller\role.js

'use strict';

const { Controller } = require('egg');

class RoleController extends Controller {
  async index() {
    const { ctx } = this;
    const res = await ctx.service.role.findRoleList();
    console.log('res', res);

    ctx.body = res; // 返回值
  }
}

module.exports = RoleController;

在这里插入图片描述

数据库查询的数据
在这里插入图片描述

数据库手动命令插入一条数据查询
在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值