Reputation: 5044
This is my basic Timesheet object query:
return TimeSheet.find({
submitDate : { '$gte': util.minDate(params.startDate), '$lte': util.maxDate(params.endDate)},
submitted: true,
user: params.userId
}, callBack(res)).populate('user timeEntries');
However, I'd like to search on submitDate
or workDate
based on a front end filter without wrapping this and another query in an if statement based on the passed in value. I'd like to do the $gte
and $lte
on a field defined by a variable.
I've looked at some other answers on here, such as this one here, but it seems to be a little simple for what I'm trying to do.
What's the proper syntax here? I've tried looking through MongoDB documentation but I can't seem to get it. Is this possible?
This is what I've tried thus far.
var query = {};
query['submitDate'] = [];
query['submitDate']['$gte'] = util.minDate(params.startDate);
query['submitDate']['$lte'] = util.maxDate(params.endDate);
Upvotes: 1
Views: 1635
Reputation: 1696
Should be very similar to the reference you've cited:
var dateFilterToUse = /*logic to populate this varibale with "submitDate" or "workDate" based on your front end filter*/;
var findJSON = {
submitted: true,
user: params.userId
};
findJSON[dateFilterToUse]= { '$gte': util.minDate(params.startDate), '$lte': util.maxDate(params.endDate)};
return TimeSheet.find(findJSON, callBack(res)).populate('user timeEntries');
Upvotes: 1