Jacek Wojcik
Jacek Wojcik

Reputation: 1253

Passing additional parameter to Mongoose query

I want to pass additional parameter to Mongoose findOne query.

Here is my pseudo code:

for (var i = 0; i < 5; i++) {
    SomeCollection.findOne({name: 'xxx' + i}, function (err, document) {
        if (document) {
            console.log('aaa' + i + document.somefield);  
        }
    });
}  

As you can see I am using i variable value in a findOne callback, since it is run in different thread I want to pass it to findOne method.

How can I do it?

Upvotes: 1

Views: 1027

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

As long as you're using node.js 4.x or above, you can effectively create a new scope per iteration by using let instead of var in your for loop:

for (let i = 0; i < 5; i++) {
    SomeCollection.findOne({name: 'xxx' + i}, function (err, document) {
        if (document) {
            // i will have the same value from the time of the findOne call
            console.log('aaa' + i + document.somefield);  
        }
    });
}

Upvotes: 3

Related Questions