Nested populate match query

Viewed 19

Here is an example of the data I am working with:

// group
{
    name: 'Group 1',
    phases: [ {name: 'Period 1', startDate: "some date", endDate: "someDate", schedules: [{startTime: '1:00', endTime: '2:00', schedule: 'mongoIdRef'}]}, { name: 'Period 2', startDate: "some date", endDate: "someDate", schedules: []}, { name: 'Period 3', startDate: "some date", endDate: "someDate", schedules: []}, { name: 'Period 4', startDate: "some date", endDate: "someDate", schedules: [] } ]
}
// schedule
{
    condition: 'active',
    tz: 'US/Mountain',
    daysOfWeek: [{startTime: 9, endTime: 22, days: [2,3,4,5]}, {startTime: 2, endTime: 5, days: [2,5,6]}]
}

The group's nested "schedule" property needs to get populated. I am doing this successfully here:

Group.statics.findForDate = function (date) {
    date = moment(date);

    return this.findForDate({
        phases: {
            $elemMatch: {
                startDate: {$lte: date},
                endDate: {$gte: date }
            }
        }
    }).populate( {
        {
            path: 'phases.schedules.schedule',
            match: {'daysOfWeek': { $elemMatch: {days: date.day() } } }
        }
    })
}

However, the match doesn't match properly. I want to return only groups that have a schedule that has the date.day() (which is a number 0-6) in the days array. How can I get .match to do this? Is there another approach?

0 Answers
Related