I'm currently stuck on trying to figure out a certain problem using Mongoose with Node.js and MongoDb. I have records in my mongodb plan collection that have the plan date split among 3 different fields, one for storing year, one for month, and one for day - all Number fields. For instance, the date 7/4/2014 would be stored like so:
_id: fjewifjweifja...
Name: "test plan name"
PlanDateYear: 2014
PlanDateMonth: 7
PlanDateDay: 4
I am trying to construct a mongoose query that will return me all the plan records that exist between a specified start and end date range. I have the query working for getting plans between start and end date range if all the plans dates happen to be in the same year, however if some of the plans dates cross over into another year then the mongoose query logic gets all whacky. Is there some concise way to do this within the constraints of having the fields in the plan collection: PlanDateYear, PlanDateMonth, and PlanDateDay?
Thanks so much for your help! I've been stuck on this for awhile now :(
Here's my current query:
Plan.find({
'user': req.user.id,
"$or" : [
{
'planDateMonth': startDateMonth,
"$and" : [
{ "planDateDay" : {$gte: startDateDay} }
,{'planDateMonth': {$ne: endDateMonth}}
//,{'planDateYear': {$gte: startDateYear}}
]
},
{
'planDateMonth': endDateMonth,
"$and" : [
{ "planDateDay" : {$lte: endDateDay} }
,{'planDateMonth': {$ne: startDateMonth}}
]
},
{
'planDateMonth': {$ne: endDateMonth},
"$and" : [
{'planDateMonth': {$ne: startDateMonth}},
{'planDateMonth': {$lte: endDateMonth, $gte: startDateMonth}},
{'planDateDay': {$lte: endDateDay, $gte: startDateDay}}
]
},
{
'planDateMonth': endDateMonth,
"$and" : [
{'planDateMonth': startDateMonth},
{'planDateDay': {$lte: endDateDay, $gte: startDateDay}}
]
}
]
}
)
.exec(function (err, plans) {
if (err) return next(err);
else {
//do stuff
}
I would find a way to work with Mongo Dates, or use integer to represent dates (YYYYMMDD) since simple math comparisons work as expected on them.