tbo*_*nst 11 javascript database mongodb node.js
我刚刚开始使用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回调,因此如果您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);});
});