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;

 

猜你喜欢

转载自www.cnblogs.com/loaderman/p/11570991.html