Friday, 28 April 2017

Cant send data back to client with Node.js post request with for loop

I have a post request which I need to loop through an array, find the users in the database and sent the results back to the view but I can only seem to send back the first user. How are for-loops supposed to be implemented? I cant use re.send in a loop and res.JSON gives me the same result. My code below sends back the first user:

  app.post('/rankcandidates', function(req, res){
    var array = JSON.parse(req.body.array);

  for (var i = 0;i<array[0].length;i++){
   User.find({"_id" : { "$in" : [ array[0][i]._id] }
        }).exec(function (err, result) {

          res.setHeader('Content-Header', 'application/json');
          res.send(JSON.stringify(result));
          // also tried res.JSON but doesn't work 
          });
        }
          });

My Ajax call:

   $.post("/rankcandidates",
   {array:JSON.stringify(array)},
   function(data,status){
     console.log(data); // comes out as a string of the first user
   });



via user

No comments:

Post a Comment