0

I have some users in the mongodb/mongoose database and I want to put all their names of people in the same zip code into an array.

var namesArray = [];

Users.find({ zip: '55555' }, function ( err, people ) {
  for ( i = 0, i < people.length, i++ ) {
    namesArray[i] = people.name // How do I specify which person to use if they're all being returned at once?
  };
});
UX Guy
  • 257
  • 2
  • 13
  • "people" will already be returned as array from the "find" method. You can do with it as you like. Check out `.forEach` – aarosil Sep 29 '14 at 21:59
  • 1
    I love you. I wish I could give you upvote points. I'm trying to upvote your comment. – UX Guy Sep 29 '14 at 22:01
  • You'll want to access an index of `people` in the same way you're already doing with `namesArray` -- `namesArray[i] = people[i].name;` – Jonathan Lonowski Sep 29 '14 at 22:01
  • 1
    Also, with the structure of your snippet, for a possible future question: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Jonathan Lonowski Sep 29 '14 at 22:04

1 Answers1

0

Use this code

 var namesArray=[];
Users.find({ zip: '55555' }, function ( err, people ) {
  for ( i in people) {
    namesArray[i] = people[i]
  };
});
Harutyun Abgaryan
  • 2,013
  • 1
  • 12
  • 15