![](/img/trans.png)
[英]node.js mongodb - collection.find().toArray(callback) returns empty
[英]node.js mongodb - collection.find().toArray(callback) - callback doesn't get called
我剛剛開始使用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
回調,所以如果你想在創建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);});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.