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

285
Visualizações
Why i can't insert a number of values into Firebase through loop?

Im just trying to insert a number of values into Firebase, for analysis reasons. In fact, im testing the database for a university project. The idea was to get the time it takes to insert and retrieve data.

The code im doing is simple, but it wont insert into the database the number of messages i want.

function sendMessage(times){

    for(let i = 0; i < times; i++){

        console.log(i); // this prints 50 times

        let messageObj = {
           user: "testUser" + i,
           message: "message" + i
        };

        firebase.database().ref("History/" + Date.now()).set(messageObj); // this executes only a random number of times

}

window.onload = function () {

    sendMessage(50);

}

Here is an image of the data inserted into Firebase Realtime Database.

enter image description here

As you can see, the data is being inserted in a random way. Why is this happening? Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Using Date.now() for your node name is going to lead to multiple nodes ending up on the same millisecond. And since keys in Firebase are unique by definition, that means that you're overwriting the previous result on the same timestamp.

A slightly better approach is to also embed the value of i in the key, which ensures they are always unique:

firebase.database().ref("History/" + i + "_" + Date.now()).set(messageObj)

Even better would be to use Firebase's built-in push operations, which prevents this type of problem (and many others) entirely:

firebase.database().ref("History/").push(messageObj)
about 4 years ago · Juan Pablo Isaza 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