在查询中从查询访问MongoDB值 [英] Accessing a MongoDB value from a query within a query

查看:82
本文介绍了在查询中从查询访问MongoDB值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当您将循环与异步代码和闭包一起使用时,可以在运行异步代码之前对闭包进行高级设置(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.

这篇关于在查询中从查询访问MongoDB值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆