I have been trying to use promises to fulfill assign people to shifts by finding the person who has worked in the least amount of time. To this I'm using aggregate to link each individual person's availability document with their record document that contains the last time they worked. It seems it is skipping over the whole section of code that has to do with promises because it is printing selectedPeopleList as an empty array. Here's my code:
var selectedPeopleList = [];
var sequentially = function(shifts) {
var p = Promise.resolve();
shifts.forEach(function (){
p=p.then( function() { return collection.aggregate([
{
$lookup:
{
from: "personRecord",
localField: "ATTU_ID",
foreignField: "ATTU_ID",
as: "record"
}
},
{
$match : { 'Available[]' : { $elemMatch : { $eq : shift.value } }, "record.ATTU_ID": { $nin : _.map(selectedPeopleList, 'ATTU_ID') } }
},
{
$sort : { "record.lastShift" : 1 }
}
]).toArray(function(err, docs){
assert.equal(err, null);
}).then(function (result) {
if(docs && docs.length) {
selectedPeopleList.push({ ATTU_ID : docs[0].ATTU_ID, Name: docs[0].Name });
console.log(docs[0]);
}
});
});
})
return p;
};
console.log(selectedPeopleList);