Node.js mongoose按带条件的填充字段对文档进行排序
我有两个模式Node.js mongoose按带条件的填充字段对文档进行排序,node.js,mongodb,mongoose,database-design,Node.js,Mongodb,Mongoose,Database Design,我有两个模式 车辆模式: const VehicleSchema = new Schema({ title: { type: String, required: true }, price: { type: Number, required: true }, ); VehicleSchema.virtual('promotions', { ref: 'Promotion', localField: '_id', foreignField: 've
车辆
模式:
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);
促销
模式:
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);
每个车辆
都有多个促销活动
,其中一个促销活动处于活动状态(开始时间小于日期。现在
和结束时间大于日期。现在
)
1-我需要获得所有具有一个促销(现在处于活动状态)的车辆,并按start\u在
2-是否可以添加名为is\u promotion
的虚拟字段,并将其设置为true(如果有活动促销)
注意:可能有一些车辆
没有任何促销
#尝试获取我们车辆模式的起始位置,然后使用find()在所有促销模式的车辆模式字段中搜索此位置#
你可以用
$lookup promotions by vehicle id,用于获取最新促销的标准、排序和限制
添加is_促销字段
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]}
}}
])
我需要得到所有车辆,而不仅仅是有促销活动的车辆
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]}
}}
])