mongoose 安装
npm i egg-mongoose -S
config/plugin.js
mogoose: {
enable: true,
package: 'egg-mongoose',
}
config/config.default.js
config.mongoose = {
url: 'mongodb://localhost:27017/runoob',
option: {
server: {
poolSize: 40,
},
},
router
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.get('/add', controller.home.add);
router.get('/find', controller.home.find);
router.get('/insert', controller.home.insert);
router.get('/deleteOne', controller.home.delete);
router.get('/deleteMany', controller.home.deleteMany);
};
controller
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, egg';
}
async add() {
const result = await this.ctx.service.user.add();
this.ctx.body = result;
}
async find() {
const query = this.ctx.query;
console.log('query:', query);
const result = await this.ctx.service.user.find(query);
this.ctx.body = result;
}
async insert() {
const query = this.ctx.query;
const result = await this.ctx.service.user.insert(query);
this.ctx.body = result;
}
async delete() {
const query = this.ctx.query;
const result = await this.ctx.service.user.deleteOne(query);
return result;
}
async deleteMany() {
const query = this.ctx.query;
const result = await this.ctx.service.user.deleteMany(query);
return result;
}
}
module.exports = HomeController;
service
'use strict';
const Service = require('egg').Service;
class UserService extends Service {
async add() {
const result = await this.ctx.model.User.create({
name: 'xiaoMinghui',
age: '20',
sex: '1',
});
return result;
}
async find(query) {
const result = await this.ctx.model.User.find(query);
return result;
}
async insert(query) {
const result = await this.ctx.model.User.create(query);
return result;
}
async deleteOne(query) {
const result = await this.ctx.model.User.deleteOne(query);
return result;
}
async deleteMany(query) {
const result = await this.ctx.model.User.remove(query);
return result;
}
}
module.exports = UserService;
model 定义
'use strict';
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
},
age: {
type: String,
},
sex: {
type: String,
},
});
return mongoose.model('User', UserSchema, 'test');
};