Louis Vetter
Louis Vetter

Reputation: 309

Organizing user/post relation in a database

Using the Firebase database I need to decide how to organize the user / post(e.g a tweet) relation. Two common reading tasks include:-

  1. Showing an overview of a user's posts
  2. Filtering and selecting specific posts based on their content

I currently use this:

posts
    randproject1234jdfs
         user_uid: randomUserName1234,
         content: "example"

users
     randomUserName1234
         posts 
              project_id: randproject1234jdfs
         nickname: "Mr Example"

This stores the same information twice:

  1. In posts/randstring1234jdfs/user_uid , the value points to the user.
  2. In users/1234/posts the project_id point to the post.

Would removing one of these lead to significantly slower data-reading (having to loop through the entire folder to see if the user_uid/project_id matches the given post/user)?

Or would it be better to organize the data in a different way altogether (e.g removing the user/posts split)?

Upvotes: 0

Views: 225

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80934

You want to do the following:

Showing an overview of a user's posts

Filtering and selecting specific posts based on their content

You can do this then:

posts
   randomid
     user_uid: randomUserName1234,
     content: "example"
     posttitle: "English"
   randomid2
     user_uid: randomUserName1235,
     content: "examples"
     posttitle: "Math"

users
 randomUserName1234 <-------------------- userid
          email: [email protected]
          nickname: "Mr Example"
 randomUserName1235<--------------------anotheruserid
           email: [email protected]
           nickname: "Mr Awesome"

Since you want to show the user's post, then you can just query the node posts something like this: orderByChild(user_uid).equalTo(randomUserName1234) using that you can retrieve the content which are the posts I guess.

To retrieve posts of any user depending on content using the above u can do this:

orderByChild("posttitle").equalTo("English") and then retrieve the node content which I'am assuming they are the posts.

Remember denormalization is normal and it is important or you will have a hard time doing the queries. https://firebase.googleblog.com/2013/04/denormalizing-your-data-is-normal.html

The user node let it have the list of users in this app for example.

The posts node will be like above and it will be connected to the user by having this user_uid: randomUserName1235 as seen above.

Upvotes: 1

Related Questions