手把手使用 Egg+TypeScript+mongoDB快速实现增删改查

创建一个Egg的TS项目(Egg.js官方教程)

安装MogoDB Egg 依赖

npm install  egg-mongoose -g

也可以在某个文件中测试mongoDB链接

import mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/test');
const con = mongoose.connection;
con.on('error', console.error.bind(console, '连接数据库失败'));
con.once('open', () => {
  console.log('连接成功');
});

下载完成后添加对应mongodb插件到Egg 中

app/congif/plugin.ts 文件中添加

import { EggPlugin } from 'egg';

const plugin: EggPlugin = {
  mongoose: {
    enable: true,
    package: 'egg-mongoose',
  },
};

export default plugin;

app/congif/config.default.ts 中添加

  config.mongoose = {

    client: {
      url: 'mongodb://127.0.0.1:27017/test', // test是数据库得名字
      options: {
        useNewUrlParser: true,
      },
    },
  };

在这里插入图片描述

新建模型(model)文件夹 在app文件夹下面

app/model/article.ts

export default app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  // 验证规则
  const ArticleSchema = new Schema({
    sendMessage: {
      type: String,
      minlength: [ 2, '字符串度不能小于2' ],
      maxlength: [ 10, '字符串度不能大于10' ],
    },
    id: {
      type: Number,
      // 主键必填
      required: [ true, '传入ID' ],
    },
    type: {
      type: String,
      minlength: [ 2, '字符串度不能小于2' ],
      maxlength: [ 5, '字符串度不能大于10' ],
    },
  }, { versionKey: false });

  return mongoose.model('Article', ArticleSchema, 'artcle'); // Article在service中调用的名称 ArticleSchema是验证的字段规则  artcle是你数据集合表的名称
};

在控制器(controller)文件夹中添加 article.ts 文件

app/controller/article.ts

import { Controller } from 'egg';


export default class articleController extends Controller {
  // 获取列表
  async index() {
    const { ctx } = this;
    const res = await ctx.service.article.getProjectById();
    ctx.body = res; // 返回值显示
  }
  // 添加数据
  async addmongDB() {
    const { ctx } = this;
    const dataList = await ctx.service.article.add();
    ctx.body = {
      status: 200,
      data: dataList,
    };
  }

  // 根据id 查询
  async asyncid() {
    const { ctx } = this;
    const { id } = ctx.request.body || {};
    ctx.body = await ctx.service.article.searchID(id);
  }
  // 修改数据
  async updateData() {
    const { ctx } = this;
    const { id, type, sendMessage } = ctx.request.body || {};
    ctx.body = await ctx.service.article.updata(id, type, sendMessage);
  }
  // 删除
  async deleId() {
    const { ctx } = this;
    const { id } = ctx.request.body || {};
    ctx.body = await ctx.service.article.deleId(id);
  }
}

在服务(service)文件夹中新建 article.ts

app/service/article.ts

import { Service } from 'egg';

export default class blogdbService extends Service {

  public async getProjectById() {
    const { ctx } = this;
    try {
      const results = await ctx.model.Article.find();
      return results;
    } catch (err) {
      console.log('Service -Error ', err);
      ctx.body = JSON.stringify(err);
    }
  }

  // 根据id 查询数据
  public async searchID(id: number) {
    const { ctx } = this;
    try {
      console.log('searchID--->', id);

      const results = await ctx.model.Article.find({ id }, { sendMessage: 1, id: 1, tyep: 1, _id: 0 });
      return results;
    } catch (err) {
      console.log('Service -Error ', err);

      ctx.body = JSON.stringify(err);
    }
  }

  // 添加数据
  public async add() {
    const { ctx } = this;
    try {
      const addBlog = new ctx.model.Article({ id: 99, type: 'video', sendMessage: '视频播放' });
      return await addBlog.save();
    } catch (error) {
      console.log('Service - add -Error ', error);
      return error;
    }
  }
  // 修改数据
  public async updata(id: any, type: any, sendMessage: any) {
    const { ctx } = this;
    try {
      await ctx.model.Article.updateOne({ id }, { type, sendMessage }, {}, (Err: any, result: any) => {
        console.log(Err, result);

      });
    } catch (error) {
      console.log('Service - add -Error ', error);
      return error;
    }
  }
  // 删除
  public async deleId(id) {
    const { ctx } = this;
    try {
      await ctx.model.Article.deleteOne({ id });
    } catch (error) {
      console.log('Service - add -Error ', error);
      return error;
    }
  }
}

标题注入路由

import { Application } from 'egg';

export default (app: Application) => {
  const { controller, router, middleware } = app;

  router.get('/article', controller.article.index);
  router.get('/articleAdd', controller.article.addmongDB);
  router.post('articleid', controller.article.asyncid);
  router.post('/articleupdate', controller.article.updateData);
  router.post('/articledeleId', controller.article.deleId);
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值