Beslinda N.
Beslinda N.

Reputation: 5316

How to flatten data on Firebase

I am developing an application where users post products inside categories. I am using firebase and I am trying to flatten the data on the database but I am not sure about the connections of the posts with the categories.

Here is the database design:

"categories": {
  "category1": {
     "id": "1",
     "name":  "computers"  
   },
  "category2": {
     "id": "2",
     "name":  "Furniture"  
    },
  "category3: {
    "id": "3",
    "names":  "Books" 
   },
}
"users":{
  "email": "[email protected]"       
  "posts": {
    "post1": {
       "id": "1"
       "title": "Selling my guitar”,
       "categories": {
         "category1": "true"
        }
      }
  }

Edit: Maybe smth like this

"categories": {
  "category1": {
     "id": "1",
     "name":  "computers",
     "posts": {
        "post1": true
     }
   },
  "category2": {
     "id": "2",
     "name":  "Furniture"
   },
  "category3": {
    "id": "3",
    "names":  "Books"
   },
}
"users": {
  "userid1": {
    "email": "[email protected]" ,
    "posts": {
      "post1": "true"
    }
  }
 },

 "posts": {
    "post1": {
       "id": "1",
       "title": "Selling my guitar",
       "users": {
         "user1" : "true"
       },
       "categories": {
         "category1": "true"
        }
      }
  } 

So from what I learnt I know posts should be a separate entity but then I am not sure how to connect them.

Let me know how can I improve this database.

Upvotes: 2

Views: 935

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

Flattening data means that you don't mix entity types. If you look at your current /users node, you now information about the user there (their email address) and a list of nodes. Those are two distinct entity types and should normally be in separate top-level lists.

"categories": {
  "category1": {
     "id": "1",
     "name":  "computers"  
   },
  "category2": {
     "id": "2",
     "name":  "Furniture"  
    },
  "category3: {
    "id": "3",
    "names":  "Books" 
   },
}
"users":{
  "userid1": {
    "email": "[email protected]"       
  }
 },
 "posts": {
    "post1": {
       "id": "1"
       "title": "Selling my guitar”,
       "categories": {
         "category1": "true"
        }
      }
  }

Upvotes: 3

Related Questions