The first function in my async waterfall is one that takes an _id as input and uses the findOne() method to get two attributes from the document with that particular _id. I then pass these two attributes in a callback to the next function in the waterfall. Here is the non-working code:
async.waterfall([
function (callback) {
Results.findOne({ _id:match_id }, function (result) {
var match_date = result.match_date;
var match_week = result.week;
});
callback(match_date, match_week);
},
function (match_date, match_week) {
// ...
// do something with the date and week ...
I see the problem is that the callback is getting called while the findOne method is still executing, hence the variables are undefined and the process crashes.
I understand that I need to structure the code so that the callback is called only when mongoose finishes querying the database, however I'm not sure how to do this and have read every relevant post here and still can't get my head around it.
Any help would be great, thank you.
Well, you should do it inside mongoose callback:
async.waterfall([
function (callback) {
Results.findOne({_id:match_id}, function(result) {
...
callback(match_date, match_week);
});
},
...
]);