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

293
Vistas
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 Respuestas
Responde la pregunta

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 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