view raw
cerealex cerealex - 7 months ago 62
Javascript Question

Firebase sorting and filtering

I'm trying to filter blog entries through url params containing the url property of its categories array."foo-bar"

I want to list every entry that has the filter param in its categories array url value.

This is the entry composition.

- Title
- Content
- Categories
-[0]{Name: "foo bar", Url: "foo-bar"}
-[1]{Name: "Other", Url: "other"}

How would this be achieved?

I´ve tried a couple of things with
but nothing worked.


With Firebase and other NoSQL database structures, there is a practice called denormalization that helps with sorting and filtering. The basic idea is to have the same data in multiple formats, designed for a specific task. So in your case, you might have something like this:

blogEntries: {
  blogId1: {
    Title: '...',
    Content: '...',
    Categories: [ 'categoryId1', 'categoryId2', ... ]
  ... more blog entries ...
blogCategories: {
  categoryId1: {
    Name: '...',
    Url: '...'
  ... more categories ...
blogEntriesByCategories: {
  'foo bar': [ blogId1, blogId5, ... ],
  'other': [ blogId3 ],

You would then do your search on blogEntriesByCategories to get all the blog IDs where it matches 'foo bar' for example, then cross reference those IDs with the data under blogEntries that match the respective blog ID.

With Firebase 3, you can write to multiple paths simultaneously. So any time you add, update, or delete a blog entry you would also update blogEntriesByCategories. This blog entry has a great write up on how that is done with Firebase 3.

Hope this helps!