Firebase Two foreach duplicating data

Asked

Viewed 75 times

0

Friends, I started developing using Firebase not long ago. I’m "stuck" in a part of development where I’m using a foreach inside another foreach that’s oddly duplicating the results. When I see the result inside the console.log return without the duplicity. The purpose of the code is to generate a list of people.

Structure: collection(Viagensconfirmed)/document(id)/collection(Passengers)/document(id)/collection(passenger list)

//ler e carregar documento viagem para impressão relatorio
carregar = function(id){
	var qtd = 0;
	var content = '';
	content +="<tr>";
	var table = document.getElementById("ex-table");
firestore.collection("ViagensConfirmadas").where("IdViagem", "==", id).get().then(function(querySnapshot) {
   	querySnapshot.forEach(function(doc) {
      var val = doc.data();
      //inicio for para pegar os passageiros
firestore.collection("ViagensConfirmadas/"+doc.id+"/Passageiros").get().then(function(queryySnapshot) {
				queryySnapshot.forEach(function(docc) {
					var pass = docc.data();
					content += "<td>" + pass.Nome + "</td>";
					content += "<td>" + pass.CPF + "</td>";//cpf
					content += "<td>" + pass.RG + "</td>";//rg
					//fim for para pegar os passageiros
					content += "<td>" + val.Telefone + "</td>";
					content += "<td>" + val.Nome + "</td>";
					content += "<td>" + val.Origem + "</td>";
					content += "<td>" + val.Destino + "</td>";
					content += "</tr>";
					console.log(pass.Nome);//AQUI ESTOU TENTO O RETORNO SEM DUPLICIDADE
				});
				qtd = qtd + val.QuantidadePassageiros;
				document.getElementById("qtd").value = qtd;//AQUI RETORNAR O VALOR CORRETO
				var text = content;
				table.innerHTML += text
			});
		});
	});
}

Inside the collection Viagensconfirmed I have 3 documents. Where the result presented is being written as follows:

The first document registered at the bank (there are 3 passengers in this document) is being written two times;

Then write the second document registered in the bank (there is 1 passenger in this document);

Then write the first document and the second one again, and finally the third document registered in the bank (there are 3 passengers in this document), as if it were a second loop, already going through all the documents.

Stay like this:

Pass1	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass2	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass3	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass1	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass2	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass3	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass4	CPF	identidade	00-00000-0000	Resp2	Origem	Destino
Pass1	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass2	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass3	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass4	CPF	identidade	00-00000-0000	Resp2	Origem	Destino
Pass5	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass6	CPF	identidade	00-00000-0000	Resp1	Origem	Destino
Pass7	CPF	identidade	00-00000-0000	Resp1	Origem	Destino

I’m already looking for a qualification regarding Firebase, but I’m on a tight deadline for this project. So come humbly and ask for the support of all of you.

1 answer

0


Hello, the error is happening because you are not cleaning the variable content after allocating the consultation.

Here is an example of how it should be corrected

...
            table.innerHTML += text

            content = '';
          });
...

However, how you are using asynchronous requests within the first forEach will overwrite the previous data

I took the liberty of refactoring your code in order for you to apply your script more clearly.

/* eslint-disable */

var montaHTML = function(viagem, passageiro) {
  return `
  <tr>
    <td>${passageiro.Nome}</td>
    <td>${passageiro.CPF}</td>
    <td>${passageiro.RG}</td>
    <td>${viagem.Telefone}</td>
    <td>${viagem.Nome}</td>
    <td>${viagem.Origem}</td>
    <td>${viagem.Destino}</td>
  </tr>
  `
}

var carregar = function (id) {
  // carrega elementos
  var table = document.getElementById("ex-table");
  var qtd = document.getElementById("qtd");

  firestore
    .collection("ViagensConfirmadas")
    .where("IdViagem", "==", id)
    .get()
    .then(function(viagens) {

      viagens.forEach(function(doc) {
        var viagem = doc.data();

        qtd.value = (qtd.value || 0) + viagem.QuantidadePassageiros;

        firestore
          .collection(`ViagensConfirmadas/${doc.id}/Passageiros`)
          .get()
          .then(function(passageiros) {

            passageiros.forEach(function(doc) {
              var passageiro = doc.data();

              // monta HTML conforme as requisições vão carregando
              table.innerHTML = `${table.innerHTML}${montaHTML(viagem, passageiro)}`;
            })
          })

      })
    })
}
  • Luke! Thank you very much for your help. May God bless you, for your kindness and humility to be willing to help. For the time I have added the "content = '';" to the code, but I will study your suggestion better presented in the reformulation, for better the script.

  • I’m very grateful to help, anything I can do

Browser other questions tagged

You are not signed in. Login or sign up in order to post.