Friday, 21 June 2019

mongoose sort document by populated field with conditions

i have two schema

vehicle schema :

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 Schema :

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);

every vehicle have multi Promotion and one of Promotions is active(start_at less then Date.now and end_at greater then Date.now)

1- i need to get all Vehicles with one Promotion(that now active) and sort its by start_at

2- is it possible to add virtual field with name is_promotion and set it to true if have active Promotion?

note: It is possible that some Vehicle do not have any Promotion



from mongoose sort document by populated field with conditions

No comments:

Post a Comment