从查询中的查询访问MongoDB值

Accessing a MongoDB value from a query within a query

本文关键字:查询 MongoDB 访问      更新时间:2023-09-26

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

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

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

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的值更改)。这意味着您可能访问了错误的元素,或者完全访问了无效的元素。将异步函数封装在一个自关闭函数中可以确保被封装的函数使用正确的项。