0

Why does being inside a second query cause this field to be undefined? Here's the code:

Survey.findById(req.params.id, function(err, survey) {

        for ( var i=0; i<=survey.businesses.length-1; i++ ) {

            console.log(survey.businesses[i].votes); // This returns the expected value

            UserSurvey.find({ surveyId: req.params.id, selections: survey.businesses[i].id }, function(err, usurvey) {

                console.log(survey.businesses[i].votes); // businesses[i] is undefined

            });
        }

});

1 Answer 1

1

There are a couple problems with your approach. I would recommend doing something like this instead:

Survey.findById(req.params.id, function(err, survey) {
    for ( var i=0; i<=survey.businesses.length-1; i++ ) {
        (function(business) {
            console.log(business); // This returns the expected value
            UserSurvey.find({ surveyId: req.params.id, selections: business.id }, function(err, usurvey) {
                console.log(business.votes); // businesses[i] is undefined
            });
        })(survey.businesses[i]);
    }
});

When you use a loop with async code and a closure, it's possible for the closure to be advanced (the value of i changes) before the async code is run. That means you may be accessing either the wrong element, or an invalid element altogether. Wrapping the async function in a self closing function ensures that the correct item is used by the wrapped function.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent - makes sense and worked perfectly. Thanks a lot for this. Much to learn!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.