javascript 遍历猫鼬查找结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15853304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:19:46  来源:igfitidea点击:

Iterate through mongoose find result

javascriptmongoose

提问by Pio

I have some trouble getting out data from the result of a query in mongoose: here is my function:

我在从 mongoose 中的查询结果中获取数据时遇到了一些麻烦:这是我的函数:

getNinjas : function(res){
    var twisted = function(res){
        return function(err, data){
            if (err){
                console.log('error occured');
                return;
            }
            res.send('My ninjas are:\n');
            for (var i;i<data.length;i++){
                console.log(data[i].name);
            }
                            //I need to process my data one by one here
        }
    }

    Ninja.find({},'name skill',twisted(res));
}

So if I console.log(data)in the getNinjas function, I get the result of my query. How can I access each record one by one? I get nothing in the console like this.

所以如果我console.log(data)在 getNin​​jas 函数中,我会得到我的查询结果。如何一一访问每条记录?我在控制台中什么也得不到。

回答by robertklep

You forgot to initialize i:

你忘了初始化i

for (var i = 0;i<data.length;i++){
//        ^^^^
  console.log(data[i].name);
}

回答by Ali

Since you ask how to access each record one by one, it's good to have forEachin your arsenal other than the standard forloop. Once you've crossed the error checking if:

由于您询问如何逐条访问每条记录,因此forEach除了标准for循环之外,最好在您的武器库中使用。一旦你越过错误检查if

data.forEach(function(record){
    console.log(record.name);
    // Do whatever processing you want
});