title: Cloud Firestore and data modeling: From RDBMS to No-SQL
body: <p>I am building an iOS app that is using Cloud Firestore (not Firebase realtime database) as a backend/database.</p>
  
  <p>Google is trying to push new projects towards Cloud Firestore, and to be honest, developers with new projects should opt-in for Firestore (better querying, easier to scale, etc..).</p>
  
  <p>My issue is the same that any relational database developer has when switching to a no-SQL database: <strong>data modeling</strong></p>
  
  <p>I have a very simple scenario, that I will first explain how I would configure it using MySQL:</p>
  
  <p>I want to show a list of posts in a table view, and when the user clicks on one post to expand and show more details for that post (let say the user who wrote it). Sounds easy.</p>
  
  <p>In a <strong>relational database world</strong>, I would create 2 tables: one named "<strong>posts</strong>" and one named "<strong>users</strong>". Inside the "<strong>posts</strong>" table I would have a <em>foreign key</em> indicating the user. Problem solved.</p>
  
  <p><a href="https://i.stack.imgur.com/ux3I8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ux3I8.png" alt="enter image description here"></a></p>
  
  <p><em>Poor Barry, never had the time to write a post :(</em></p>
  
  <p>Using this approach, I can easily achieve what I described, and also, if a user updates his/her details, you will only have to change it in one place and you are done.</p>
  
  <p>Lets now switch to Firestore. I like to think of RDBMS's table names as Firestore's collections and the content/structure of the table as the documents.</p>
  
  <p>In my mind i have 2 possible solutions:</p>
  
  <p><strong>Solution 1:</strong></p>
  
  <p>Follow the same logic as the RDBMS: inside the <strong>posts</strong> collection, each document should have a key named "userId" and the value should be the documentId of that user. Then by fetching the posts you will know the user. Querying the database <strong>a second time</strong> will fetch all user related details.</p>
  
  <p><strong>Solution 2:</strong></p>
  
  <p>Data duplication: Each post should have a map (nested object) with a key named "user" and containing any user values you want. By doing this the user data will be attached to every post it writes.</p>
  
  <p>Coming from the normalization realm of RDBMS this sounds scary, but a lot of no-SQL documents encourage duplication(?). </p>
  
  <ul>
  <li>Is this a valid approach?</li>
  <li>What happens when a user needs to update his/her email address? How easily you make sure that the email is updated in all places?</li>
  </ul>
  
  <p>The only benefit I see in the second solution is that you can fetch both post and user data in one call.</p>
  
  <p>Is there any other solution for this simple yet very common scenario?</p>
  
  <p>ps: go easy on me, first time no-sql dev.</p>
  
  <p>Thanks in advance.</p>