Patrioticcow
Patrioticcow

Reputation: 27038

how to structure data in Firebase?

i come from a MySQL workflow and now i am trying to do something in Firebase, and i have some dilemmas with structuring my data, because i don't know how would i query it.

fallowing the example below where i have some users and some comments, what is a good way to find

how many post likes a user had
how many post comments a user had
what were the posts that a user liked
...

i was thinking on adding that information to a user, like:

  "user:2": {
    "name": "Doe",
    "email": "[email protected]",
    "post_likes": {
      "post:1": 1,
      "post:2": 1
    },
    "post_comments": {
      "post:1": 15,
      "post:2": 5
    }
  }

but this seems redundant and duplicates data..

i need to find a way to search in posts everything that has to do with user:1, maybe i need to create another object that connects the users and posts ??

any ideas?

{
  "array": {
    "users": {
      "user:1": {
        "name": "John",
        "email": "[email protected]"
      },
      "user:2": {
        "name": "Doe",
        "email": "[email protected]"
      }
    },
    "posts": {
      "post:1": {
        "name": "First Post",
        "content": "some post content",
        "comments": {}
      },
      "post:2": {
        "name": "Second Post",
        "content": "some other post content",
        "likes": 2,
        "comments": {
          "comment:1": {
            "uid": "user:1",
            "email": "some comment"
          },
          "comment:2": {
            "uid": "user:2",
            "email": "some other comment"
          }
        }
      }
    }
  }
}

Upvotes: 2

Views: 255

Answers (1)

Kato
Kato

Reputation: 40582

How to structure data is not a simple question to answer and is highly dependent on how the data will be read. The general rule is to work hard on writes to make reads easy. Firebase offers two guides on understanding data and on structuring data.

They won't fit nicely into this text box, so you'll find better answers there. Here's a birds-eye view.

  1. It's JSON data.
  2. Flatten your data. Don't nest just because you can. Treat each logical data component like you would in SQL and keep it in its own path.
  3. Avoid arrays in distributed systems. Sequential numeric ids are error prone.
  4. Utilize indices to create sub-lists of master data rather than trying to nest lists in lists in lists.

Upvotes: 2

Related Questions