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.
.collection()is asynchronous. The results are not available immediately.