Rhys Edwards Rhys Edwards - 7 months ago 17
Javascript Question

Select Dates for Weekends Only

I'm trying to query my mongoDB collection to return documents that include the field

selectedDate
and check if the date string falls on a weekend (saturday[6] or sunday[0]).

How do I pass the field's value to the function to check it?
data
returns undefined but I am unsure how to store it in a var properly.

Query

Entry.
find({}).
where('selectedDate').equals(thisWeekend(data)).
exec(function(err, entries) {
console.log('Events on a weeked' + ' ' + entries);
});


Function

function thisWeekend(data) {
var today = data.getDay();
if (today == 6 || today == 0) {
console.log('WEEKEND BITCHES');
} else {
console.log('Not the weekend');
}
};

Answer

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.

Comments