cursor.toArray(callback)不返回文档数组

Gar*_*res 5 javascript mongodb node.js

我想返回一个包含甲板集合文档的数组.我可以让光标指向那些文档,然后我使用toArray()函数将它们转换为数组.

问题是我无法返回已转换的数组...请查看我的代码.

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...
};
Run Code Online (Sandbox Code Playgroud)

老实说,我不知道results在外围范围内发生了什么.我究竟做错了什么?如何results以找到的文档数组的形式返回.

ver*_*loc 15

正如@Pointy所指出的那样,该行return results是在调用之前同步执行的,collection.find它返回了任何结果.

解决这个问题的方法是提供函数的回调,如下所示:

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);
        });
    }); 
};
Run Code Online (Sandbox Code Playgroud)

为了更好地理解回调的工作原理,请查看此答案.是的,异步编程起初很难,并且确实需要一些人习惯.