Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cursor.toArray(callback) does not return an array of documents

I want to return an array that contains documents of the decks collection. I can get the cursor to point to those documents and then I use the toArray() function to turn them into an array.

The problem is that I cannot return the converted array... please take a look at my code.

exports.find_by_category = function (category_id){
    var results = []; //Array where all my results will be
    console.log('Retrieving decks of category: ' + category_id);
    mongo.database.collection('decks', function(err, collection) {
        collection.find({'category_id': category_id}).toArray(function(err,items){
            results = items; //Items is an array of the documents
        });
    }); 
    return results; //The problems is here, results seems to be empty...
};

I honestly dont know what is going on since results is in the outer-scope. What am I doing wrong? How can I achieve returning results as an array of the found documents.

like image 925
Gary Torres Avatar asked Dec 19 '13 22:12

Gary Torres


1 Answers

As @Pointy pointed out, the line return results is executed synchronously, way before the call to collection.find has returned any results.

The way to solve this is to provide a callback to the function, like so:

exports.find_by_category = function (category_id, callback){ //Notice second param here  
    mongo.database.collection('decks', function(err, collection) {
       collection.find({'category_id': category_id}).toArray(function(err,items){
           if(err) callback(err);
           else callback(null, items);
        });
    }); 
};

For a better understanding of how callbacks work, check out this answer. And yes, async programming is hard at first, and does require some getting used to.

like image 162
verybadalloc Avatar answered Sep 22 '22 10:09

verybadalloc