實作 mongodb 資料庫增删改查
建立 egg 項目
$ mkdir egg-mongoose-demo && cd egg-mongoose-demo
$ npm init egg --type=simple
$ npm i
安裝 egg-mongoose
npm i egg-mongoose --save
egg 配置
// config\plugin.js
module.exports = {
mongoose: {
enable: true,
package: 'egg-mongoose'
}
};
mongoose 連接配接配置
// config\config.default.js
config.mongoose = {
url: 'mongodb://127.0.0.1:27017/test' // test 為 mongodb 資料庫
};
定義 mongoose 資料模型
app 檔案夾下建立 model 檔案夾 建立 user.js 定義 schema
// app\model\user.js
'use strict';
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const UserSchema = new Schema({
userName: { type: String },
password: { type: String },
});
return mongoose.model('User', UserSchema, 'user');
}
定義控制器
// app\controller\user.js
'use strict';
const Controller = require('egg').Controller;
class UserController extends Controller {
async find() {
this.ctx.body = await this.ctx.service.user.find();
}
async insert() {
this.ctx.body = await this.ctx.service.user.insert();
}
async delete() {
this.ctx.body = await this.ctx.service.user.delete();
}
async update() {
this.ctx.body = await this.ctx.service.user.update();
}
}
module.exports = UserController;
定義服務
// app\service\user.js
'use strict';
const Service = require('egg').Service;
class UserService extends Service {
async find() {
console.log('UserService find doing')
return await this.ctx.model.User.find({});
}
async insert() {
console.log('UserService insert doing')
return await this.ctx.model.User.create({'userName': 'wq_test', 'password': 123});
}
async delete() {
console.log('UserService delete doing')
return await this.ctx.model.User.remove({'userName': 'wq_test'});
}
async update() {
console.log('UserService update doing')
return await this.ctx.model.User.update({'userName': 'wq_test'}, {$set:{'userName':'wq'}});
}
}
module.exports = UserService;
建立路由
// app\router.js
'use strict';
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.get('/find', controller.user.find);
router.get('/insert', controller.user.insert);
router.get('/delete', controller.user.delete);
router.get('/update', controller.user.update);
};
啟動項目
npm run dev
測試增删改查
[插入資料測試](http://127.0.0.1:7001/insert)
[查詢資料測試](http://127.0.0.1:7001/find)
[更新資料測試](http://127.0.0.1:7001/update)
[删除資料測試](http://127.0.0.1:7001/delete)