0

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:

enter image description here

jrDeveloper
  • 167
  • 2
  • 10
  • check what `results` is in `.toArray(function(err, result)` because if `db.findMostRecentDate` is actually `function findMostRecentDate` then your code seems to do the right thing – Jaromanda X Oct 03 '17 at 01:24
  • You cannot `return arr.concat(datesColl);`. Your `getDates` function must use an asynchronous callback as well – Bergi Oct 03 '17 at 01:27
  • you're right @Bergi , but that code is *after* the error :p – Jaromanda X Oct 03 '17 at 01:30
  • This is pretty much a duplicate of [How do I return a value from my asynchronous call](https://stackoverflow.com/a/14220323/816620). Once ANY part of your function or any functions you call are asynchronous, the whole result becomes asynchronous and the ONLY way to communicate back the result is with a callback, a promise or some other delayed notification scheme (like a promise). `getDates()` is asynchronous and CANNOT return your value directly. It must use a callback or a promise to return the result just like `findMostRecentDate()` does. – jfriend00 Oct 03 '17 at 02:14
  • In addition to the above note about returning a value from `getDates()`, you also apparently are doing something wrong with your `db.collection().find().sort().toArray()` because it appears that `result` is `undefined when you call the callback. – jfriend00 Oct 03 '17 at 02:18
  • @jfriend00 @Bergi if I understand the two of you correctly, I basically 'cheated' by trying to wrap my async `findMostRecentDate()` inside `getDates()`--a function with the usual synch approach. If I want this to work, then `getDates()` needs to take a callback? I'll put all my computations in there? – jrDeveloper Oct 03 '17 at 03:47
  • @jrDeveloper - Yes, that is correct. But, if `start` is `undefined` inside of `getDates()`, then you have another problem too as my previous comment says. – jfriend00 Oct 03 '17 at 03:51
  • @jfriend00 Re `start`: you're not saying the variable declaration is suspect? Rather, that something might be wrong with my `findRecentDate()` method? I'm going to isolate it piece by piece tomorrow morning and see if I can find a better approach. Thanks, appreciate your time and patience explaining these things to me. – jrDeveloper Oct 03 '17 at 04:08
  • @jrDeveloper - Nothing to do with the variable declaration. It's what you're putting in it. Just use `console.log(...)` or breakpoints in the debugger to track the value you have and see where it is good or not. – jfriend00 Oct 03 '17 at 04:10

0 Answers0