手把手使用 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);
};

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的示例,演示如何使用 Vue3 和 TypeScript 实现表格的增删改查功能: ```typescript <template> <div> <table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="(item, index) in dataList" :key="index"> <td>{{ item.name }}</td> <td>{{ item.age }}</td> <td> <button @click="edit(index)">编辑</button> <button @click="remove(index)">删除</button> </td> </tr> </tbody> </table> <div> <input v-model="form.name" type="text" placeholder="姓名" /> <input v-model="form.age" type="text" placeholder="年龄" /> <button @click="save">保存</button> </div> </div> </template> <script lang="ts"> import { defineComponent } from 'vue'; interface DataItem { name: string; age: string; } export default defineComponent({ data() { return { form: { name: '', age: '', }, dataList: [] as DataItem[], editIndex: -1, }; }, methods: { save() { if (this.editIndex === -1) { this.dataList.push(this.form); } else { this.dataList.splice(this.editIndex, 1, this.form); this.editIndex = -1; } this.form = { name: '', age: '', }; }, edit(index: number) { this.form = { ...this.dataList[index] }; this.editIndex = index; }, remove(index: number) { this.dataList.splice(index, 1); }, }, }); </script> ``` 在上面的代码中,我们使用了 `interface` 定义了一个 `DataItem` 的数据类型,它包括了 `name` 和 `age` 两个字段。然后在 `data` 函数中,我们定义了 `form`、`dataList` 和 `editIndex` 三个变量,分别表示表单数据、数据列表和编辑行的索引。 接着,在 `methods` 中,我们定义了三个方法:`save`、`edit` 和 `remove`。其中,`save` 方法用于保存表单数据并将其添加到数据列表中或者更新数据列表中的某一项;`edit` 方法用于编辑某一行的数据;`remove` 方法用于删除某一行的数据。 最后,在模板中,我们使用了 `v-for` 指令遍历数据列表,并使用 `v-model` 指令绑定表单数据。同时,我们使用了 `@click` 指令绑定了 `save`、`edit` 和 `remove` 方法。 需要注意的是,上面的示例只是一个最基本的实现,还有很多细节和优化可以进行,例如表单验证、分页、搜索等等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值