Home > other >  Why i can't insert a number of values into Firebase through loop?
Why i can't insert a number of values into Firebase through loop?

Time:11-09

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.

CodePudding user response:

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)
  • Related