Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

289
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!