当前位置:Gxlcms > 数据库问题 > Egg中使用Mongoose实现数据库表的关联查询

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

时间:2021-07-01 10:21:17 帮助过:6人阅读

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实现数据库表的关联查询

标签:wait   module   lookup   使用   username   mongo   agg   extend   sync   

人气教程排行