我刚开始使用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);
});
}
});
};
每当我尝试dao。 findAll(错误,回调)时,回调永远不会被调用。 我已将问题缩小到代码的以下部分:
collection.find().toArray(function(error, result){
//... whatever is in here never gets executed
});
我看过其他人是怎么做到的。事实上,我非常关注this tutorial。没有其他人似乎对colelction.find()。toArray()有这个问题,并且它没有出现在我的搜索中。
谢谢, Xaan。
答案 0 :(得分: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);});
});