npm i egg-mongoose --save
// config/plugin.js
'use strict';
exports.ejs = {
enable: true,
package: 'egg-view-ejs',
};
// 配置egg-mongoose插件
exports.mongoose = {
enable: true,
package: 'egg-mongoose'
};
// config/config.default.js
'use strict';
module.exports = appInfo => {
const config = exports = {};
config.keys = appInfo.name + '_1534304805936_5738';
config.middleware = [];
exports.view = {
mapping: {
'.html': 'ejs',
},
};
// 第一种配置方式
// exports.mongoose = {
// url: 'mongodb://127.0.0.1/test',
// options: {},
// };
// 第二种配置方式(推荐)
// 配置mongoose数据库
exports.mongoose = {
client: {
// 有用户名和密码的数据库的连接方式
// url:'mongodb://admin:123456@localhost:27017/test'
url: 'mongodb://127.0.0.1/test',
options: {},
},
};
return config;
};
// app/model/user.js
module.exports = app => {
// 引入建立连接的mongoose
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
// 数据库表的映射
const UserSchema = new Schema({
username: { type: String },
password: { type: String },
status: {
type: Number,
default: 1
}
});
return mongoose.model('User', UserSchema, 'user');
}
领域模型一般放置在 app/model 下面,可选,由领域类相关插件约定。
// app/controller/user.js
'use strict';
const Controller = require('egg').Controller;
class UserController extends Controller {
// 查询用户
async index() {
// 建议将操作数据库的方法放到service里
var userList = await this.ctx.model.User.find({});
this.ctx.body = '用户列表页面';
}
// 增加用户
async addUser() {
// 建议将操作数据库的方法放到service里
var user = new this.ctx.model.User({
username: '张三',
password: '123456'
});
var result = await user.save();
this.ctx.body = '增加用户成功';
}
// 编辑用户
async editUser() {
// 建议将操作数据库的方法放到service里
await this.ctx.model.User.updateOne({
"_id": "5b84d4405f66f20370dd53de"
}, {
username: "李四",
password: '456789'
}, function (err, result) {
if (err) {
console.log(err);
return;
}
})
this.ctx.body = '修改用户成功';
}
// 删除用户
async removeUser() {
// 建议将操作数据库的方法放到service里
var result = await this.ctx.model.User.deleteOne({
"_id": "5b84d4b3c782f441c45d8bab"
});
// 需要对result作出判断
this.ctx.body = '删除用户成功';
}
}
module.exports = UserController;
// app/model/order.js
// 定义Order的schema,生成模型
module.exports = app => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
var OrderSchema=Schema({
order_id:String,
uid:Number,
trade_no:String,
all_price:Number,
all_num:Number
});
return mongoose.model('Order',OrderSchema,'order');
}
生成了订单表的模型后,就可以关联查询订单详情了。
// app/controller/order.js
'use strict';
const Controller = require('egg').Controller;
class OrderController extends Controller {
async index() {
// 实现关联查询
var orderResult = await this.ctx.model.Order.aggregate([
{
$lookup: {
from: 'order_item',
localField: 'order_id',
foreignField: 'order_id',
as: 'items'
}
},
{
$match: { "all_price": { $gte: 90 } }
}
]);
this.ctx.body = orderResult;
}
}
module.exports = OrderController;