我刚开始使用 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(error, callback),callback 永远不会被调用。 我已将问题缩小到代码的以下部分:
collection.find().toArray(function(error, result){
//... whatever is in here never gets executed
});
我研究过其他人是如何做到的。其实我在关注this tutorial很接近的。 colelction.find().toArray() 似乎没有其他人有这个问题,而且它没有出现在我的搜索中。
谢谢, 夏安。
最佳答案
您没有使用 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);});
});
关于javascript - node.js mongodb - collection.find().toArray(callback) - 回调不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078194/