安装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);
};