Accessing A MongoDB Value From A Query Within A Query
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.
Solution 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.
Post a Comment for "Accessing A MongoDB Value From A Query Within A Query"