Search code examples
angularjsfirebasefirebase-realtime-databaseangularfire

Is it possible to get an array of unique values in firebase?


Consider the following data stored in Firebase:

{
  "beers": {
    "-jwhkclclmecl": {
      "name": "Two Hearted Ale",
      "type": "IPA",
      "brewery": "Bells"
    },
    "-ckqjheh292od": {
      "name": "Dirty Blonde Ale",
      "type": "Pale Wheat",
      "brewery": "Atwater"
    },
    "-hcwiu3cp902d": {
      "name": "Diabolical",
      "type": "IPA",
      "brewery": "North Peak"
    }
  }
}

Is it possible to build a query for Firebase to return an array of the unique values of one of the child nodes. For example to return ["IPA", "Pale Wheat"]


Solution

  • Nope, you cannot query a collection for unique values of a specific property of each item. You can filter on such values, so ref.child('beers').orderByChild('type').equalTo('IPA'). But that's not what you were asking. :-)

    Typically if you want this type of operation in Firebase (or most other NoSQL databases), you'll keep the items (or references to the items) under a group:

    {
      "beer_types": {
        "IPA": {
          "-jwhkclclmecl": {
            "name": "Two Hearted Ale",
            "brewery": "Bells"
          },
          "-hcwiu3cp902d": {
            "name": "Diabolical",
            "brewery": "North Peak"
          }
        },
        "Pale Wheat": {
          "-ckqjheh292od": {
            "name": "Dirty Blonde Ale",
            "brewery": "Atwater"
          },
        }
      }
    }
    

    Of course that only works if you want to only keep them in one category. If you want multiple categories, you can store references to each item under multiple categories:

    {
      "beers": {
        "-jwhkclclmecl": {
          "name": "Two Hearted Ale",
          "type": "IPA",
          "brewery": "Bells"
        },
        "-ckqjheh292od": {
          "name": "Dirty Blonde Ale",
          "type": "Pale Wheat",
          "brewery": "Atwater"
        },
        "-hcwiu3cp902d": {
          "name": "Diabolical",
          "type": "IPA",
          "brewery": "North Peak"
        }
      }
      "beer_types": {
        "IPA": {
          "-jwhkclclmecl": true,
          "-hcwiu3cp902d": true
        },
        "Pale Wheat": {
          "-ckqjheh292od": true
        }
      },
      "breweries": {
        "Bells": {
          "-jwhkclclmecl": true
        },
        "Atwater": {
          "-ckqjheh292od": true
        }
        "North Peak": {
          "-hcwiu3cp902d": true
        }
      }
    }