I'm writing some JS code that does the following: it will query a Mongo DB for some results. Assuming a collection of documents comes back, it will search for the most recent date of the collection of objects, compute some missing dates and then insert them in (the actual method doing the computations is working fine).
For some reason I am getting an error that when I try to access the week
property of the start
object, it is coming back undefined
. It seems like I don't understand how to properly structure my code. What I want/hope is that the code in the else condition gets executed once the result comes back from findMostRecentDate
, but it looks like the code is getting executed before the result comes back. I pasted the little error I get back from the console.
Can someone please give me some assistance on how to restructure my code?
I have broken my task down into several functions below:
Finds the most recent date based off the parameters passed. This works fine when I run it on it's own:
// Finds the most most recent date of the collection
function findMostRecentDate(contract_id, case_id, callback){
db.collection(getCollectionName(contract_id, config.collectionName))
.find({"by": case_id}).sort({week: -1}).toArray(function(err, result) {
if (err) {
return callback(err);
}
return callback(null, result);
});
}
The following method will make a call to the method listed above:
function getDates(datesColl, length, contract_id, case_id){
var start;
var arr = [];
if(length > 1) {
db.findMostRecentDate(contract_id, case_id, function(err, result){
if(err) {
console.error(err); //log it with winston logger!
} else{
start = result; //<--coming back 'undefined'
//newRows does some computations.
arr = newRows(start.week, case_id);
return arr.concat(datesColl);
}
});
}
else{
//do some other stuff
}
}
I get the following error: