从查询中的查询中访问MongoDB值

时间:2014-10-31 19:42:49

标签: javascript node.js mongodb mongoose

为什么在第二个查询中导致此字段未定义?这是代码:

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 个答案:

答案 0 :(得分:1)

您的方法存在一些问题。我建议做这样的事情:

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]);
    }
});

当您使用具有异步代码和闭包的循环时,可以在异步代码运行之前提升闭包(i的值更改)。这意味着您可能正在访问错误的元素或完全无效的元素。在自闭合函数中包装异步函数可确保包装函数使用正确的项。