Search code examples
javascriptangularjsfirebaseangularfire

Retrieving only the parent elements from firebase : Angularfire


enter image description here

The image shows the structure of my database. I want to print 1, 2 ... (so on) i.e. the parent element names alone. But couldn't understand how to do that.


Solution

  • The Firebase Database is essentially one JSON object.

    This object is in a tree structure. If you read from one location in the tree, you'll get each piece of data underneath it.

    Take a look at this sample database.

    {
      "items": {
        "1": {
          "title": "Hi"
        },
        "2": {
          "title": "Bye"
        }
      }
    }
    

    There is no way with the JavaScript SDK or AngularFire, to only read the parent keys of 1 and 2 under "items".

    If you only want to read the parent keys, you'll need to create an index for them in the Firebase database.

    {
      "items": {
        "1": {
          "title": "Hi"
        },
        "2": {
          "title": "Bye"
        }
      },
      "itemKeys": {
        "1": "Hi",
        "2": "Bye"
      }
    }
    

    Now you can create a reference at the itemKeys location and pass that to a $firebaseArray() or $firebaseObject().

    var ref = new Firebase('<my-firebase-app>.firebaseio.com/itemKeys');
    var syncArray = $firebaseArray(ref);
    

    If you're concerned with keeping two separate data structures consistent, check out the client-side fan-out feature.