Node.js中筛选Availability日期大于当前日期的数据,$gte函数位置咨询
解决Mongoose中筛选关联文档日期大于当前日期的问题
嘿,我明白你现在的困扰——想从Booking记录里筛选出关联的Availability日期大于今天的条目,不知道该把$gte放在哪儿对吧?别着急,我给你两种实用的解决方案,你可以根据自己的场景选:
方案一:基于现有代码修改(快速上手)
这个方案直接在你原来的populate操作里加过滤条件,然后在结果里筛掉不符合的记录,改动很小:
首先,先确保你的今日日期是正确的Date对象,建议重置到凌晨,避免时间部分干扰:
var today = new Date(); today.setHours(0, 0, 0, 0); // 把时间设为00:00:00,确保从当天开始算
然后修改populate('slotId')的部分,加上match选项来过滤日期:
getBookingList(){ return new Promise(function(resolve,reject){ var today = new Date(); today.setHours(0, 0, 0, 0); Booking.find( {userId: req.userId} ) .populate({ path:'expId', model:Experiences }) .populate({ path:'slotId', model:Availability, // 这里的`date`要替换成你Availability模型里实际的日期字段名,比如`availableDate` match: { date: { $gte: today } } }) .exec(function(err,result){ if(err){ reject(err); } else { // 过滤掉那些没有匹配到符合日期条件的Availability的Booking记录 const validBookings = result.filter(booking => booking.slotId !== null); if(validBookings.length > 0){ resolve(validBookings); } else { resolve({"msg":"Booking Experiences not found."}); } } }); }); }
方案二:用聚合查询(更高效)
如果你的数据量比较大,不想把所有Booking都查出来再在内存里过滤,那用聚合查询更合适——直接在数据库层面完成关联和过滤:
getBookingList(){ return new Promise(function(resolve,reject){ var today = new Date(); today.setHours(0, 0, 0, 0); Booking.aggregate([ // 第一步:先筛选当前用户的所有Booking { $match: { userId: req.userId } }, // 第二步:关联Availability集合,同时过滤日期大于今天的记录 { $lookup: { from: "availabilities", // 这里填Availability模型对应的集合名,一般是复数小写 localField: "slotId", foreignField: "_id", as: "slotId", pipeline: [ { $match: { date: { $gte: today } } } // 同样替换成实际的日期字段名 ] } }, // 第三步:去掉没有匹配到有效Availability的记录 { $match: { slotId: { $ne: [] } } }, // 第四步:把slotId数组转成单个对象(因为原来的关联是一对一) { $unwind: "$slotId" }, // 第五步:关联Experiences集合 { $lookup: { from: "experiences", // 填Experiences模型对应的集合名,复数小写 localField: "expId", foreignField: "_id", as: "expId" } }, { $unwind: "$expId" } ]).exec(function(err, result){ if(err){ reject(err); } else { result.length > 0 ? resolve(result) : resolve({"msg":"Booking Experiences not found."}); } }); }); }
小提示:
- 一定要替换代码里的
date字段为你Availability模型中实际存储日期的字段名,比如如果你的字段叫availabilityDate,就改成availabilityDate: { $gte: today }。 - 聚合查询里的集合名要注意是模型名的复数小写形式(Mongoose默认会自动转换),如果你的集合名自定义过,要改成对应的名称。
内容的提问来源于stack exchange,提问作者dev dev
相关产品推荐
相关产品推荐

