Egg中使用Mongoose实现数据库表的关联查询
model/user.js
module.exports = app => { const mongoose = app.mongoose; /*引入建立连接的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'); }
modle/order.js
module.exports = app => { const mongoose = app.mongoose; /*引入建立连接的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'); }
controller/order.js
'use strict'; const Controller = require('egg').Controller; class OrderController extends Controller { async index() { //实现关联查询 // var orderResult=await this.ctx.model.Order.find({}); 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;
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!