Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda