我有两个模式
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,并且促销 Activity 之一(start_at小于Date.nowend_at大于Date.now)

1-我需要通过一次促销(现在处于 Activity 状态)获取所有载具,并按start_at对其进行排序

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

注意:某些Vehicle可能没有任何Promotion

最佳答案

您可以使用 $lookup

按车辆ID进行$ lookup促销,以获取条件,排序和限制以获取最新促销。

$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]}
  }}
])

关于node.js - Mongoose 按填充字段按条件对文档进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56617034/

10-11 01:48