1

In my Firebase Realtime Database I have a structure like this:

Database Screenshot

Now I want to implement a function that adds habits to this collection. Right now I am using the following code (with input.value being the value of an input element). However, the Firebase push method creates a random key everytime it adds a new element. I would like the keys to be numbers / index values, just like the elements in the screenshot have the keys 0 and 1. Is there a Firebase method that works like this (if so, I couldn't find it), and if not, how would I best implement this, so that the next element would be added with the key 2 and so on?

function addHabit() {
  push(reference(database, "habits"), {
    text: input.value,
    interval: "Daily",
  });
}
Ralph
  • 37
  • 6
  • There is no such method. Best is to grab the `habits` node itself and since it's just JSON on the client, count the children, then add another node with key corresponding to the new number. Or, you don't try to replicate arrays and save a field like "timestamp" to or "position" to each value and [sort it](https://firebase.google.com/docs/database/web/lists-of-data#sort_data) when retrieving data from Firebase RTDB. – b2m9 Apr 06 '22 at 08:52
  • If It Works Keep Another Node Inside `habits` named something like `eventcount` then just get the `eventcountno` from it then add a node to `habits` and increment `eventcountno`. This works if there are multiple users trying to create a node at the same time. (It Costs More Reads And Writes Though) – mrtechtroid Apr 06 '22 at 14:59

1 Answers1

1

Using sequential numeric keys with Firebase is an anti-pattern as determining the next index requires you to read the existing length (so won't work while offline) and that all users agree on that length (so won't work in multi-user scenarios). To store lists of data, it's better to use Firebase's push() operator.

For more on this, see Best Practices: Arrays in Firebase.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807