arraysfirebasefirebase-realtime-databasefirebase-console

Setting arrays in Firebase using Firebase console


I am using Firebase console for preparing data for a demo app. One of the data item is attendees. Attendees is an array. I want to add a few attendees as an array in Firebase. I understand Firebase does not have arrays, but object with keys (in chronological order). How do I do that for preparing sample data? My current Firebase data looks like the below. enter image description here


Solution

  • The Firebase Database doesn't store arrays. It stores dictionaries/associate arrays. So the closest you can get is:

    attendees: {
      0: "Bill Gates",
      1: "Larry Page",
      2: "James Tamplin"
    }
    

    You can build this structure in the Firebase Console. And then when you read it with one of the Firebase SDKs, it will be translated into an array.

    firebase.database().ref('attendees').once('value', function(snapshot) {
      console.log(snapshot.val());
      // ["Bill Gates", "Larry Page", "James Tamplin"]
    });
    

    So this may be the result that you're look for. But I recommend reading this blog post on why Firebase prefers it if you don't store arrays: https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html.

    Don't use an array, when you actually need a set

    Most developers are not actually trying to store an array and I think your case might be one of those. For example: can "Bill Gates" be an attendee twice?

    attendees: {
      0: "Bill Gates",
      1: "Larry Page",
      2: "James Tamplin",
      3: "Bill Gates"
    }
    

    If not, you're going to have to check whether he's already in the array before you add him.

    if (!attendees.contains("Bill Gates")) {
      attendees.push("Bill Gates");
    }
    

    This is a clear sign that your data structure is sub-optimal for the use-case. Having to check all existing children before adding a new one is going to limit scalability.

    In this case, what you really want is a set: a data structure where each child can be present only once. In Firebase you model sets like this:

    attendees: {
      "Bill Gates": true,
      "Larry Page": true,
      "James Tamplin": true
    }
    

    And now whenever you try to add Bill Gates a second time, it's a no-op:

    attendees["Bill Gates"] = true;
    

    So instead of having to code for the uniqueness requirement, the data structure implicitly solves it.