Compare data structures for firebase blog app

时间:2019-04-16 22:24:30

标签: firebase firebase-realtime-database nosql

function writeNewPost(uid, username, picture, title, body) {
  // A post entry.
  var postData = {
    author: username,
    uid: uid,
    body: body,
    title: title,
    starCount: 0,
    authorPic: picture
  };

  // Get a key for a new Post.
  var newPostKey = firebase.database().ref().child('posts').push().key;

  // 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;

  return firebase.database().ref().update(updates);
}

The code above is from firebase official doc. My question is, can I use this approach to implement a feature like uses' favorite list? If I use this approach, I will get the following data structure:

 posts:{
      cYlevsDysdfsd:{
          author: 'John Doe',
          uid: sfIsdfNsAOQ,
          body: 'Hello world!',
          title: 'My first post',
          starCount: 0,
          authorPic: picture
      }
}


user-posts:{
    sfIsdfNsAOQ:{
          cYlevsDysdfsd:{
              author: 'John Doe',
              uid: sfIsdfNsAOQ,
              body: 'Hello world!',
              title: 'My first post',
              starCount: 0,
              authorPic: picture
          }
    }
}

user-favs:{
        Ysfdwefwezc:{
              cYlevsDysdfsd:{
              author: 'John Doe',
              uid: sfIsdfNsAOQ,
              body: 'Hello world!',
              title: 'My first post',
              starCount: 0,
              authorPic: picture
        }
    }
}

We can see that the postData of the post with the Id cYlevsDysdfsd is repeating again and again. If I have more attributes in postData, this approach will take more space in the database. So I wonder if the following data structure will be better:

user-posts:{
    sfIsdfNsAOQ:{
          cYlevsDysdfsd,
          second_Post_Id,
          third_Post_Id
    }
}

user-favs:{
    Ysfdwefwezc:{
          cYlevsDysdfsd,
          second_Fav_Post_Id,
          third_Fav_Post_Id
    }
}

In the second approach, I only save the postId in the users' favlist and post list. When I need the post data, I just fetch the data under the /posts path based on the postId using a for loop. But this approach seems require more http requests. Which way is better?

0 个答案:

没有答案