[英]Stuck on Node + MongoDB asynchronous query issue
A little preface: I am very new to working with Node so please bear with my ignorance 一个小小的序言:我对与Node合作非常陌生,所以请无知承担
I am trying to pass some info from an array in Node.js, and check whether it exists in a MongoDB document. 我正在尝试从Node.js中的数组传递一些信息,并检查它是否在MongoDB文档中存在。 I am still struggling to wrap my head around Node and how to work with databases asynchronously.
我仍在努力地围绕Node以及如何异步使用数据库进行工作。
I have the following code 我有以下代码
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
});
});
}
In the above code, I have an array of strings called articleTitle
(for example: ['Title1', 'Title2', 'Title3']
), I then run through each of those titles in the array (using the for()
loop) to check if each title exists in the database. 在上面的代码中,我有一个名为
articleTitle
的字符串数组(例如: ['Title1', 'Title2', 'Title3']
),然后遍历数组中的每个标题(使用for()
循环) )检查数据库中是否存在每个标题。
The output I get is as follows: 我得到的输出如下:
> Title1
> Title2
> Title3
> No results found for title: Title 3
> No results found for title: Title 3
> No results found for title: Title 3
As evident above it seems to be checking for the last object in the array three times. 如上所示,它似乎正在检查数组中的最后一个对象三次。 I have also tried to implement the async package but struggled with that as well.
我也曾尝试实现异步包,但也为此感到困惑 。
Any help would be appreciated. 任何帮助,将不胜感激。
The issue you have is scope of the variable i
in the callback function. 您遇到的问题是回调函数中变量
i
范围。
Use for (let i in articleTitle)
instead. 使用
for (let i in articleTitle)
代替)。 This creates a new variable i for every iteration and scope is restricted to that iteration. 这将为每个迭代创建一个新变量i,并且作用域仅限于该迭代。
The answers to this question JavaScript closure inside loops – simple practical example explain in detail about why this happens and about scope and closure in JavaScript. 这个问题的答案是循环内的JavaScript封闭-一个简单的实际示例详细说明了这种情况的发生原因以及JavaScript的作用域和封闭。 The above question is an exact duplicate of this question.
上面的问题与该问题完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.