我有两个模式
车辆
架构:
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);
每个 vehicle
都有多个 Promotion
并且其中一个 Promotion 处于事件状态(start_at
小于 Date.now
和end_at
大于 Date.now
)
1- 我需要获得所有具有一项促销事件(现已激活)的车辆,并按 start_at
2- 是否可以添加名称为 is_promotion
的虚拟字段并将其设置为 true(如果有事件促销)?
注意:有些Vehicle
可能没有任何Promotion
最佳答案
您可以使用 $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]}
}}
])
关于node.js - Mongoose 按条件填充字段排序文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617034/