For is looped through but only executes the find() function inside after 3 iterations

Viewed 91

I'm trying to get the information from all vehicles present in the database, through their license plates. When I execute the code, it loops 3 times, which is how many cars are currently registered and then it acts werid. First, it only gives back the car the last car that got in, which makes it only print out the last license plate, then it keeps printing 3 3 3 and only the last license plate, instead of each of the ones present in the database (see image below).

My objective is to list the information from all of the vehicles through this.

This is the code I am working:

exports.pesquisar_parque_veiculos =  function (req, res) {
    Event.findById(req.params.id).exec()
        .then(result => {
            if (!result) {
                return res
                    .status(404)
                    .jsonp({"message": "Id do parque não foi encontrado"});
            }
            var des = result.designacao;
            var loc = result.localização_GPS;
            var pr15 = result.preco_15;
            var pr1 =  result.preco_1;
            var lot =  result.lotacao;
            var lot_p =  result.lotacao_parque;
            ES.find({'parque': result.id,'estado': 'atual'}).exec()
                .then(result3 => {
                    if (!result3[0]) {
                        return res
                            .status(404)
                            .jsonp({"message": "O parque não tem veiculos estacionados"});
                    }
                    var texto = "Designação do parque: " + des +"\n Localização GPS: "+ loc +"\n Preco de 15 em 15 minutos na primeira hora: " + pr15 + "€\n Preco de 1 em 1 hora despois da primeira hora: " + pr1 + "€ \n Atualmente o parque tem " + lot + " lugares vazios dos " + lot_p + " que tem.\n" ;                   var i = 0;

                    var total =0;
                    var txt ='';
                    var matricul ='';

                    var tamanho = parseInt(result3.length) ;
                    for (var e = 0; e < tamanho; e++) {
                        matricul = result3[e].matricula;
                        var dat = result3[e].Created_data;
                        var idd =  result3[e].id;
                        total +=1;
                        texto += 'matricula:' + result3[e].matricula + '\n';

                        console.log(e);
                        Veiculo.find({'matricula':result3[e].matricula}).exec()
                          .then(result4 => {

                             if (!result4[0]) {
                                console.log(matricul);
                                console.log(e);
                                texto += "\n Matricula: " + matricul + "--- Hora de entrada: " + dat + "--Código do bilhete: " + idd;
                             }
                             console.log(matricul);
                              console.log(e);
                             var id = mongoose.Types.ObjectId(result4[0].cliente);
                             Cliente.findById(id).exec()
                                 .then(result2 => {
                                     if (!result2) {
                                        return res
                                           .status(404)
                                           .jsonp({"message": "Cliente não foi encontrado"});
                                     }
                                     if (result2[0].avenca == 'nao') {
                                         texto += "\n Matricula: " + matricul + "--- Hora de entrada: " + dat + "--Código do bilhete: " + idd;
                                     } else {
                                         texto += "\n Matricula: " + matricul + "--- Hora de entrada: " + dat + "Cliente com avenca: " + result2[0].id;
                                     }
                                 })
                                 .catch(err => {
                                     res.status(500).jsonp({
                                         error: {message: err.message}
                                     })
                                 });
                          })
                            .catch(err => {
                                res.status(500).jsonp({
                                    error: {message: err.message}
                                })
                            });
                    }
                res.send(texto);

                })
                .catch(err => {
                    res.status(400).jsonp({
                        error: {message: err.message}
                    })
                });


        })
        .catch(err => {
            res.status(400).jsonp({
                error: {message: err.message}
            })
        }) ;
}

If I send a GET request in Postman using the following code, I get the different license plates, but the find function doesn't work regardless:

texto += 'matricula:' + result3[e].matricula + '\n'; 

I get this, which displays the different license plates at the end, but it also comes from outside the find() function, which means I don't get the associated data from the license plates:

enter image description here

And this is what gets printed out to the console. I have no clue why it goes to 3. It should stop at 2. It happens because I increment the variable e, but it should still stop at 2:

enter image description here

My question is: how can I change the code in order for it to add the data from the license plate to the variable "texto" and then return said data?

0 Answers
Related