【问题标题】:mongoose sort document by populated field with conditions猫鼬按填充字段和条件对文档进行排序
【发布时间】:2019-10-30 04:54:41
【问题描述】:

我有两个架构

vehicle 架构:

const VehicleSchema = new Schema({
title: {
    type: String,
    required: true
},
price: {
    type: Number,
    required: true
},
);
VehicleSchema.virtual('promotions', {
   ref: 'Promotion',
   localField: '_id',
   foreignField: 'vehicle',
   justOne: true
});
export default mongoose.model('Vehicle', VehicleSchema);

Promotion 架构:

const PromotionSchema = new Schema({
    start_at: {
        type: Date,
        required: true
    },
    end_at: {
        type: Date,
        required: true
    },
    vehicle: {
        type: Schema.Types.ObjectId,
        ref: 'Vehicle'
    },
    amount:{
        type:Number,
        required:true
    },
});
export default mongoose.model('Promotion', PromotionSchema);

每个vehicle 都有多个Promotion,并且其中一个促销活动处于活动状态(start_at 小于Date.nowend_at 大于Date.now

1- 我需要通过一个促销(现在处于活动状态)获取所有车辆并按start_at 对其进行排序

2- 是否可以添加名称为is_promotion 的虚拟字段并将其设置为true,如果有活动的Promotion?

注意:有些Vehicle 可能没有Promotion

【问题讨论】:

    标签: node.js mongodb mongoose database-design


    【解决方案1】:

    # 尝试获取我们 VehicleSchema 的 start_at,然后使用 find() 在所有 PromotionSchema 的 VehicleSchema 字段中搜索它。#

    PromotionSchema
    .findOne({ start_at: {
            type: Date
        } })
    .populate('VehicleSchema') 
    .exec(function (err, PromotionSchema) {
      if (err) return handleError(err);
      console.log('The total vehicles %s', PromotionSchema.VehicleSchema.vehicle);
    .short(Date)
    });
    

    【讨论】:

    • 我需要获得所有车辆,而不仅仅是有促销活动的车辆
    【解决方案2】:

    您可以使用$lookup

    $lookup 按车辆 ID 的促销活动以获取标准、排序和限制以获取最新的促销活动。

    $addFields 添加 is_promotion 字段。

    VehicleSchema.aggregate([
      {"$lookup":{
        "from":"Promotion",
        "let":{"_id":"$_id"},
        "pipeline":[
          {"$match":{
            "start_at":{"$lt":Date.now},
            "end_at":{"$gt":Date.now},
            "$expr":{"$eq":["$vehicle","$$_id"]}
          }},
          {"$sort":{"start_at":-1}},
          {"$limit":1}
        ],
        "as":"activepromotion"
      }},
      {"$addFields":{
        "is_promotion":{"$gt":[{"$size":"$activepromotion"},0]}
      }}
    ])
    

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 2015-11-27
      • 2019-09-16
      • 2021-02-11
      • 2020-08-10
      • 1970-01-01
      相关资源
      最近更新 更多