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;

 

Egg中使用Mongoose实现数据库表的关联查询

上一篇:HTML5的FileAPI实现文件的读取及超大文件的上传


下一篇:InnoDB CheckPoint检查点