11

我刚开始使用 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(error, callback)回调永远不会被调用。我已将问题缩小到代码的以下部分:

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

我看过其他人是怎么做的。事实上,我非常密切地关注本教程。colelction.find().toArray() 似乎没有其他人有这个问题,而且它没有出现在我的搜索中。

谢谢,夏安。

4

1 回答 1

9

您没有使用open回调,因此如果您尝试findall在创建后立即发出请求,dao那么它将无法准备好。

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

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);});
});
于 2012-08-22T17:34:59.790 回答