I'm trying to query my mongoDB collection to return documents that include the field
selectedDate
data
Entry.
find({}).
where('selectedDate').equals(thisWeekend(data)).
exec(function(err, entries) {
console.log('Events on a weeked' + ' ' + entries);
});
function thisWeekend(data) {
var today = data.getDay();
if (today == 6 || today == 0) {
console.log('WEEKEND BITCHES');
} else {
console.log('Not the weekend');
}
};
You don't do it like that, you do it like this:
Entry.aggregate(
[
{ "$redact": {
"$cond": {
"if": {
"$or": [
{ "$eq": [ { "$dayOfWeek": "$selectedDate" }, 1 ] },
{ "$eq": [ { "$dayOfWeek": "$selectedDate" }, 7 ] }
]
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
],
function(err,results) {
if (err) throw err;
// results is weekend days only
}
)
The $redact
pipeline operator does filtering of documents by a logical expression, here using $dayOfWeek
to find the weekday value.
The alternate case is a $where
expression, but since this does require JavaScript evaluation, it actually runs much slower than the aggregation operation. You really should only use this with MongoDB 2.4 or earlier releases that do not have $redact
:
Entry.find(
{
"$where": function() {
var day = this.selectedDate.getUTCDay();
return ( day == 6 || day == 0 );
}
},
function(err,results) {
if (err) throw err;
// Just weekends
}
)
Where you really should be calling .getUTCDay()
here against a date that is in UTC.