beginner question about firestore document structure for social app
hey everyone, just started using firestore for a small social app project i'm building, and i'm totally new to nosql databases, so please bare with me. i'm a bit stuck on how to best design the document structure for user interactions like likes or comments efficiently. what are some general best practices for a beginner's document structure in firestore, especially for these types of relationships? i'm really trying to get this right from the start. thanks in advance!
2 Answers
Chisom Diallo
Answered 3 days ago-
Subcollections for Dynamic Interactions: For likes and comments, it's highly recommended to use subcollections. Instead of embedding a large array of likes or comments directly within a post document (which can hit document size limits and become inefficient for updates), create a subcollection for each.
- For a post:
/posts/{postId}/likes/{likeId} - For a post:
/posts/{postId}/comments/{commentId}
likeIddocument would typically contain theuserIdof the person who liked it and atimestamp. EachcommentIddocument would contain theuserId, thecommentText, and atimestamp. This approach ensures robust scalability for your social app, as you can have an unlimited number of likes or comments per post. - For a post:
-
Denormalization for Counts: While subcollections are great for storing the actual interactions, you'll often want to display a "like count" or "comment count" directly on the post feed without having to query the entire subcollection. For this, denormalization is your friend. Store a
likesCountandcommentsCountfield directly on the parentpostdocument. When a user likes or comments, you'd increment this counter using a batched write or a Cloud Function to ensure atomicity. This optimizes for faster reads on your main feed. -
User References: In your like and comment documents, store the
userId(the Firestore UID) of the user who performed the action. You can then fetch the user's profile details from your top-level/users/{userId}collection when needed, rather than embedding redundant user data in every interaction. - Indexing: As you start querying your data (e.g., getting all comments for a post ordered by timestamp), ensure you understand how Firestore indexes work. You might need to create custom indexes for specific query patterns to maintain performance.
Jabari Osei
Answered 2 days agoI'm actually building this out in Flutterflow, so the subcollection approach for likes and comments totally aligns with how I've been thinking about the data structure.