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.
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.
-
1
What's going on is that the call to
.collection()
is asynchronous. The results are not available immediately. – Pointy Commented Dec 19, 2013 at 22:40
1 Answer
Reset to default 15As @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.