title: Firebase (NoSQL): Denormalization vs Indexing
body: <p>Assume that I want to write a blogging app. Should I prefer one of the following two options? I would prefer to have as much "single source of truth" as possible, but I am still not sure whether that preference comes from my background in SQL.</p>
  
  <p><strong>Option 1 (Denormalization):</strong></p>
  
  <pre><code>Posts: {
    post_1: {
      title: "hello",
      body: "hi there!",
      uid: "user_1",
      comments: {
        comment_1: {
          body: "hi I commented",
          uid: "user_2",
        },
        comment_2: {
          body: "bye I commented",
          uid: "user_2",
        },
      }
    }
  }
  
  Users: {
    user_1: {
      uid: "user_1",
      post_1: {
        title: "hello",
        body: "hi there!",
        uid: "user_1",
        comments: {
          comment_1: {
            body: "hi I commented",
            uid: "user_2",
          },
          comment_2: {
            body: "bye I commented",
            uid: "user_2",
          },
        }
      }
    }
  }
  </code></pre>
  
  <p>Option 2 (Indexing):</p>
  
  <pre><code>Posts: {
    post_1: {
      title: "hello",
      body: "hi there!",
      uid: "user_1",
      authorName: "Richard",
      comments: {
        comment_1: true,
        comment_2: true
      }
    }
  }
  
  Users: {
    user_1: {
      uid: "user_1",
      displayName: "Richard",
      email: "richard@gmail.com",
      posts: {
        post_1: true
      },
      comments: {
        comment_1: true,
        comment_2: true
      }
    }
  }
  
  Comments: {
    comment_1: {
      body: "hi I commented",
      uid: "user_1",
    },
    comment_2: {
      body: "bye I commented",
      uid: "user_1",
    },
  }
  </code></pre>
  
  <p>I think I should prefer option 2.</p>
  
  <p>The main problem that I see with option 1 is that there are too many sources for one data. Let's say I want to extend the app so each post belongs to a certain category or tag. Then, I will have to write a <code>post</code> object under <code>/categories/category_id</code> in addition to <code>/posts</code> and <code>/users/uid</code>. When the post gets updated, I have to remember to modify the <code>post</code> object in three different places. If I go with option 2, I don't have this problem because there's only one source for data.</p>
  
  <p>Am I missing anything?</p>
  
  <p>References:</p>
  
  <ol>
  <li><a href="https://stackoverflow.com/questions/16638660/firebase-data-structure-and-url/16651115">Firebase data structure and url</a></li>
  <li><a href="https://firebase.google.com/docs/database/web/structure-data" rel="nofollow noreferrer">https://firebase.google.com/docs/database/web/structure-data</a></li>
  </ol>