I saw the following code from one of the firebase example apps (Link):
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
When you add a new post, it writes the same data object into two different places. This seemed odd to me because it means now there are two exactly same data that you have to take care of if you want to update or delete them. I'd rather do something like this:
post: {
id: 1,
username: 'awesomeMan', // store necessary author's metadata
title: 'hello',
body: 'body
}
author: {
id: 1,
username: 'awesomeMan',
email: 'hello@gmail.com',
posts: {
1: true // index posts by their ids
}
}
If I do it this way, I still have a bit of data duplicate because I store user's metadata username
inside a post. But isn't it better than having two exactly same data in two places?
Edit: Follow Up Question
I want to add Comments
resource to Posts
. Given these two options, which one is better, and why?
Option 1.
Store all comments related to postId
under this path:
/post-comments/${postId}
This is the only path for comments and we don't store anything into comments/
Option 2.
Store comments in comments/
and index them by ids in posts
.
/post/${postId}/comments #only consists of commentIds that belong to this post
/comments/${commentId}