04-egg如何使用-mongDB

本文详细介绍如何在Egg.js框架中使用Mongoose连接MongoDB数据库,并提供了从安装配置到实际使用的完整步骤,包括创建数据库模型、编写业务逻辑以及设置API控制器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

连接数据库

在egg.js中使用mongoose

1.egg.js官网只推荐了mysqle,要用mongodb得另找资料。通过查找,大家都在用Mongoose连接,于是乎学习**。**

网站链接:https://www.npmjs.com/package/egg-mongoose
使用方法: https://mongoosejs.com/docs/guide.html

2.第一步:安装

npm i egg-mongoose --save  

3.配置

安装完成之后在目录/config/plugin.js中引用

// config/plugin.js
exports.exports = {
    mongoose: {
    enable: true,
    package: "egg-mongoose",
  },
};

在/config/config.default.js中加入配置

// config/config.default.js
// 数据库配置
  exports.mongoose = {
    client: {
      url: 'mongodb://127.0.0.1:27017/databaseName', // 你的数据库地址,databaseName是你数据库得名字
      options: {},
    },
  };

4.使用

01- 搞个model(领域模型)文件夹 设计数据库表的格式

例子:

在app下新建文件夹model,model下新建article.js文件,完整路径app/model/article.js

// app/model/article.js
'use strict'; // 可选严格模式
 
module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  // 下面得操作是连接数据库
  const ArticleSchema = new Schema({
    // 修改和新增用到,规定字段得类型和其他条件等
    title: {
      type: String,
      required: true,
    },
    summary: {
      type: String,
    },
  }, { versionKey: false });
  // 自己创建条数据  没有数据去创建数据
  // mongoose.model('Article', ArticleSchema, 'article').create({
  //   title: "第一条",
  //   summary: "你好 mongdb",
  // });
  return mongoose.model('Article', ArticleSchema, 'article'); // Article是指定查找的入口,随便取;ArticleSchema是参数;article是你数据集合表的名称
};

02- service (务逻辑层)

这里编写逻辑(对数据库的: 增删改查)

// app/service/article.js
'use strict';
 
const Service = require('egg').Service;
 
class ArticleService extends Service {
  /**
     * 根据ID获取单个项目
     */
  async getProjectById() {
    const { ctx, app } = this;
    try {
        // 查询表 model.Article.find
      const results = await ctx.model.Article.find({ // Article为modal/article.js里面命名的名字
          // id为: xxx
        _id: app.mongoose.Types.ObjectId('5da034149b6e823ca2ea809d'),
      });
      return results;
    } catch (err) {
      ctx.body = JSON.stringify(err);
    }
  }
}
module.exports = ArticleService;

03- 控制器 编写api的入口

这在之前的课件中介绍过了

// app/controller/article.js


'use strict';
const Controller = require('egg').Controller;
 
class ArticleController extends Controller {
  async index() {
    const { ctx } = this;
    const res = await ctx.service.article.getProjectById();
    ctx.body = res; // 返回值显示
  }
}
module.exports = ArticleController;

04- 配置路由

具体在之前的课程中有介绍

// router.js
'use strict';
 
/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get('/article', controller.article.index);
};

t(’/’, controller.home.index);
router.get(’/article’, controller.article.index);
};
































































评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

厚渡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值