Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

238
Vistas
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
          }
   });

New Problem - Inserting objects into database with for loop:

   app.post('/insertPositionIndex', function(req, res){
    var array = JSON.parse(req.body.array);
    console.log(array[0]); // data shown below
    var ids;
    var indexes;

    for (var i=0;i<array.length;i++){

     ids = array[i][0].map(function(element) { return element.position_id });
     indexes = array[i][0].map(function(element) { return element.index_position });
     console.log(ids);
     console.log(indexes);
}

        User.update(
          { "_id": req.user._id},
            {
            "$push":
                {
                 "positionsApplied":{
                   position_id: ids,
                   index_position: indexes
                 }
                }
            }
        ).exec(function (err, result) {

               res.json({ results: result });
          });

    });

enter image description here

getting following error: enter image description here

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

One request can return only one response. In your case, you should first create array of user ids, and then query the user collection where you are searching all users whose id matches one element of that array. Here is a solution:

app.post('/rankcandidates', function(req, res){
    var array = JSON.parse(req.body.array);
    var ids = array[0].map(function(element) { return element._id })
    User.find({"_id" : { "$in" : ids }})
     .exec(function (err, results) {
          res.json(results);
      });
});
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda