0

i am using for loop to retrieve the data from mongodb and display it on the browser but the problem it it iterates only for the first time and stops. So i get only the first entry as the output. Whereas it gives the correct output in the console log. Please help?

var movieSchema1 = new mongoose.Schema({
  name:String,
  address:String,
  location:String
});

var user=mongoose.model('movie', movieSchema1, 'movie');

for (var i = 0; i < user.length; i++) {
  res.json("iteration " + i);
  res.json('name:' + user[i].name + user[i].address);
}
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Radhika Obhan
  • 29
  • 1
  • 5

2 Answers2

2

As others have said, build up an object for your response, then res.json() it. Because you're trying to send an array, just use .map() to transform each one:

//turn the array of users into the objects we want to send
const responseData = user.map( (movie, i) => {
   return {
      iteration: i,
      name: movie.name + ' ' + movie.address
   };
});

//this converts the array to a string for you
res.json( responseData );
Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20
0

You can use find() method to receive all of the objects from a schema.

var response;  

user.find({}, function(err, users){
       if(err) throw err;
       if(users.length != 0){
          response = users.map((user, i) => {
             return {
               index: i,
               name: user.name + ' ' + user.address
             };             
       }
    })
    for(var i = 0; i < response.length; i++){
       res.write('Key: ' i + ' the value: ' response[i] + '\n');
    }
    res.end();

You should also use res.json() once only, as it will return Can't set headers after they are sent error.

Please see this link for info on res.json()

Ahmed Can Unbay
  • 2,694
  • 2
  • 16
  • 33