Zac Webb
Zac Webb

Reputation: 663

Stuck on Node + MongoDB asynchronous query issue

A little preface: I am very new to working with Node so please bear with my ignorance

I am trying to pass some info from an array in Node.js, and check whether it exists in a MongoDB document. I am still struggling to wrap my head around Node and how to work with databases asynchronously.

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.

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.

Upvotes: 0

Views: 127

Answers (1)

The issue you have is scope of the variable i in the callback function.

Use for (let i in articleTitle) instead. This creates a new variable i for every iteration and scope is restricted to that iteration.

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. The above question is an exact duplicate of this question.

Upvotes: 2

Related Questions