【问题标题】:Accessing a MongoDB value from a query within a query从查询中的查询访问 MongoDB 值
【发布时间】:2014-10-31 19:42:48
【问题描述】:

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

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

            });
        }

});

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案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 的值会发生变化)。这意味着您可能正在访问错误的元素或完全无效的元素。将异步函数包装在自关闭函数中可确保包装函数使用正确的项目。

    【讨论】:

    • 优秀 - 很有意义并且工作完美。非常感谢。很多东西要学!
    猜你喜欢
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    相关资源
    最近更新 更多