node.js mongodb – collection.find()。toArray(callback) – callback不会被调用
我刚刚开始使用MongoDB,但是在尝试在集合上使用.find()时遇到了问题。
我创build了一个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); }); };
保存function:
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(错误,callback) , callback永远不会被调用。 我将问题缩小到代码的以下部分:
collection.find().toArray(function(error, result){ //... whatever is in here never gets executed });
我看过别人怎么做。 事实上,我正在非常仔细地学习这个教程 。 colelction.find()。toArray()没有其他人似乎有这个问题,并没有出现在我的search。
谢谢,Xaan。
你没有使用open
callback函数,所以如果你在创builddao
之后试图find所有的请求,那么它就没有准备好。
如果你的代码是这样的,它不会工作。
var dao = new DataAccessObject("my_dbase", "localhost", 27017); dao.findAll("my_collection",function() {console.log(arguments);});
我testing了它,没有findlogging,也没有错误。 我认为它应该给一个错误。
但是,如果你改变它,让你给构造函数一个callback,那么它应该工作。
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);}); });