1. 安裝模塊
npm i egg-mongoose --save
2. 配置 egg-mongoose 插件
// config/plugin.js
'use strict';
exports.ejs = {
enable: true,
package: 'egg-view-ejs',
};
// 配置egg-mongoose插件
exports.mongoose = {
enable: true,
package: 'egg-mongoose'
};
3. 配置連接數據庫的信息
// 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;
};
4. 創建 schema,生成模型
// 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 下面,可選,由領域類相關插件約定。
5. 操作數據庫
// 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;
6. 關聯查詢
// 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;