2016-04-03 129 views
2

我有一个while循环匹配一个条件来过滤来自mongodb的数据。但是,当我使用回调时,我只收到console.log的一个结果。如果我在while循环中使用console.log,我应该会收到三个条目。为什么只有一条数据使其回调?虽然循环和回调返回不同的结果

while(i--) { 
    if (0 >= [friday, saturday, sunday].indexOf(results[i].selectedDate)) { 
     theWeekend = results[i]; 
     console.log(theWeekend); //returns three results (correct) 
    } 
} 
callback(err, theWeekend) 
console.log(theWeekend); //returns one results (incorrect) 

正确性

{ _id: 56fffb5ceb76276c8f39e3f3, 
    url: 'http://londonist.com/2015/11/where-to-eat-and-drink-in-balham', 
    title: 'Where To Eat And Drink In... Balham | Londonist', 
    selectedDate: Fri Apr 01 2016 01:00:00 GMT+0100 (BST), 
    __v: 0 } 
{ _id: 56fffb8eeb76276c8f39e3f5, 
    url: 'https://news.ycombinator.com/item?id=11404770', 
    title: 'The Trouble with CloudFlare | Hacker News', 
    selectedDate: Sun Apr 03 2016 01:00:00 GMT+0100 (BST), 
    __v: 0 } 
{ _id: 56fffb6ceb76276c8f39e3f4, 
    url: 'http://wellnessmama.com/13700/benefits-coconut-oil-pets/', 
    title: 'Benefits of Coconut Oil for Pets - Wellness Mama', 
    selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST), 
    __v: 0 } 

不正确的数据

{ _id: 56fffb6ceb76276c8f39e3f4, 
    url: 'http://wellnessmama.com/13700/benefits-coconut-oil-pets/', 
    title: 'Benefits of Coconut Oil for Pets - Wellness Mama', 
    selectedDate: Sat Apr 02 2016 01:00:00 GMT+0100 (BST), 
    __v: 0 } 
+0

['Array.prototype .filter()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) – Andreas

回答

1

您需要使用一个数组来存储所有的结果如下:

var theWeekends = [] 
while(i--) { 
    if (0 >= [friday, saturday, sunday].indexOf(results[i].selectedDate)) { 
     theWeekends.push(results[i]); 

    } 
} 
callback(err, theWeekends) 
console.log(theWeekends); //returns 3 results (correct) 
+0

当然啊。谢谢 –