简体   繁体   English

在查询中从查询访问MongoDB值

[英]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.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

            });
        }

});

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. 当您将循环与异步代码和闭包一起使用时,可以在运行异步代码之前使闭包提前(i的值会更改)。 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. 在自动关闭函数中包装异步函数可确保包装函数使用了正确的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM