2

I have a while loop that matches a condition to filter data from mongodb. However, when I use the callback I only receive one result to the console.log. If I console.log inside the while loop, I should receive three entries. Why is only one piece of data making it to the callback?

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)

Correct data

{ _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 }

Incorrect data

{ _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 }
1

1 Answer 1

1

You need to use an array to store all the results as follows:

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.