我有两个模式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.now
,end_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/