繁体   English   中英

node.js mongodb - collection.find()。toArray(callback) - 不调用callback

[英]node.js mongodb - collection.find().toArray(callback) - callback doesn't get called

我刚刚开始使用mongodb,但是在尝试在集合上使用.find()时遇到了问题。

我创建了一个DataAccessObject,它打开一个特定的数据库,然后让你对它执行操作。 这是代码:

构造函数

var DataAccessObject = function(db_name, host, port){
    this.db = new Db(db_name, new Server(host, port, {auto_reconnect: true}, {}));
    this.db.open(function(){});
}

一个getCollection函数:

DataAccessObject.prototype.getCollection = function(collection_name, callback) {
    this.db.collection(collection_name, function(error, collection) {
        if(error) callback(error);
        else callback(null, collection);
  });
};

保存功能:

DataAccessObject.prototype.save = function(collection_name, data, callback){
    this.getCollection(collection_name, function(error, collection){
        if(error) callback(error);
        else{
            //in case it's just one article and not an array of articles
            if(typeof (data.length) === 'undefined'){
                data = [data];
            }

            //insert to collection
            collection.insert(data, function(){
                callback(null, data);
            });
        }
    });
}

什么似乎是有问题的 - 一个findAll函数

DataAccessObject.prototype.findAll = function(collection_name, callback) {
    this.getCollection(collection_name, function(error, collection) {
      if(error) callback(error)
      else {
        collection.find().toArray(function(error, results){
            if(error) callback(error);
            else callback(null, results);
        });
      }
    });
};

每当我试着去。 findAll(错误,回调)回调永远不会被调用。 我已将问题缩小到代码的以下部分:

collection.find().toArray(function(error, result){
    //... whatever is in here never gets executed
});

我看过其他人是怎么做到的。 事实上,我正在非常仔细地阅读本教程 似乎没有其他人对colelction.find()。toArray()有这个问题,而且我的搜索中没有出现这个问题。

谢谢,Xan。

你没有使用open回调,所以如果你想在创建dao之后立即发出findall请求,那么它就不会准备就绪。

如果您的代码是这样的,它将无法正常工作。

var dao = new DataAccessObject("my_dbase", "localhost", 27017);

dao.findAll("my_collection",function() {console.log(arguments);});

我测试了它,它没有找到记录,也没有给出任何错误。 我认为应该给出错误。

但是如果你改变它以便你给构造函数一个回调,那么它应该工作。

var DataAccessObject = function(db_name, host, port, callback){
    this.db = new Db(db_name, new Server(host, port, {auto_reconnect: true}, {}));
    this.db.open(callback);
}

并使你的代码像这样。

var dao = new DataAccessObject("my_dbase", "localhost", 27017, function() {
    dao.findAll("my_collection",function() {console.log(arguments);});
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM