cBozz
cBozz

Reputation: 37

Angularfire: how to query the values of a specific key in an array?

I have the following json object:

{
  "posts" : {
    "-Jk3ipZ2EFgvkABHf9IX" : {
      "category" : "JavaScript",
      "date" : 1426008529445,
      "heading" : "Lorem",
      "text" : "dsvgfjds daefsrgfs defsds dsfsdds",
      "user" : "Mitko"
    },
    "-Jk3jFbOOE9V8Yd37tWj" : {
      "category" : "C#",
      "date" : 1426008640253,
      "heading" : "Lorem",
      "text" : "Some Text!",
      "user" : "Peter"
    }
  }
}

I'm using Angularfire for my app. Is there a way for me to query this json and just extract the category names or am I supposed to create an additional object for the categories and query that way. I am asking because it feels redundant to query the whole array for just one value.

Thanks in advance

Upvotes: 1

Views: 893

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

Firebase's JavaScript SDK (on top of which AngularFire is built) will always load complete nodes. So there is no way to load just the category from your posts.

The common way around this is to create a second top-level node that contains just the categories; or alternatively the categories and (for each) the push-id of each post in that category.

{
  "posts" : {
    "-Jk3ipZ2EFgvkABHf9IX" : {
      "category" : "JavaScript",
      "date" : 1426008529445,
      "heading" : "Lorem",
      "text" : "dsvgfjds daefsrgfs defsds dsfsdds",
      "user" : "Mitko"
    },
    "-Jk3jFbOOE9V8Yd37tWj" : {
      "category" : "C#",
      "date" : 1426008640253,
      "heading" : "Lorem",
      "text" : "Some Text!",
      "user" : "Peter"
    }
  },
  "categories" : {
    "JavaScript" : {
      "-Jk3ipZ2EFgvkABHf9IX"
    },
    "C#" : {
      "-Jk3jFbOOE9V8Yd37tWj"
    }
}

It is a bit redundant, but allows you to get exactly the data you need to show a specific screen in your UI. Denormalizing your data like this is a common part of transitioning to a NoSQL database.

Upvotes: 4

Related Questions