有點前言:我是很新的與節點工作,所以請原諒我的無知憋屈節點+ MongoDB的異步查詢問題
我想從一個數組傳遞一些信息在Node.js的,並檢查它是否存在於MongoDB文檔中。我仍然在努力圍繞Node解決問題,以及如何異步地處理數據庫。
我有以下代碼
for (i in articleTitle) {
console.log(articleTitle[i]);
// Use connect method to connect to the Server
MongoClient.connect(mongoUrl, function(err, db) {
if (err) throw err; // Throw error
var query = { title: articleTitle[i] }; // Query Parameter
// Perform Query
db.collection(mongoCollection).find(query).toArray(function(err, result) {
if (err) throw err; // Throw error
if (result == '') {
console.log('No results found for title:', articleTitle[i]);
} else {
console.log('Found an entry');
}
db.close(); // Close connection
});
});
}
在上面的代碼中,我有字符串稱爲articleTitle
(例如:['Title1', 'Title2', 'Title3']
)的陣列,我然後通過每個陣列中的這些標題的運行(使用for()
循環)檢查每個標題是否存在於數據庫中。
我得到的輸出如下:
> Title1
> Title2
> Title3
> No results found for title: Title 3
> No results found for title: Title 3
> No results found for title: Title 3
正如上面顯然這似乎是在陣列中三次檢查的最後一個對象。我也嘗試過實施async package,但也遇到了困難。
任何幫助,將不勝感激。
完美運作。感謝您的進一步信息。 (將在7分鐘內標記爲答案; p) –