Vihanga Bandara
Vihanga Bandara

Reputation: 383

How to add data to Firebase without replacing using NodeJS?

I am trying to send a time difference between two distances from my NodeJS server to Firebase database.

function sendDatabase(dbName, payload1) {
    var timeNow = getTime();
    console.log(timeNow);
    var ref = db.ref(dbName);
    ref.set({difference:payload1});
}

dBName = IpBBEfCob0c1GaYkvAzog9rVdKn1/

payload1 is the time difference that I want to send.

dbName is a child node in the database and I want to save payload1 as child node of dbName every single time it executes.

But every time this function executes it will just replace it and no new entry will be created. I know that this is because the property name difference is the same every time, therefore I searched on Google to see if I can make it unique so that it will not replace, but I could not find a proper answer to my issue.

I am a beginner to Firebase and help with this would be much appreciated.

Upvotes: 0

Views: 1418

Answers (1)

James Poag
James Poag

Reputation: 2380

You can't have multiple instances of the same key. Then it's not a key anymore. You can't do this:

dbName
 - difference : 00
 - difference : 01
 - difference : 02
 - difference : ...

What you can do is have multiple children of difference:

dbName
  + difference
    - khghjgfvhgfh : 00
    - khghjgfvhgfi : 01
    - khghjgfvhgfj : 02
    - khghjgfvhgfk : ...

By pushing unique children:

db.ref(dbName).child("difference").push(payload1)

push automatically orders children chronologically.

And when you query your nodes, LimitToLast, First, etc...

db.ref(dbName).child("difference").limitToLast(2)

Upvotes: 3

Related Questions