3
votes

I am trying to create a simple Cloud Firestore database structure for a simple social media concept.

Each user can have at most one post (with the exception of a "most liked" post) that can be updated at any time. A user's "most liked" version of their post gets saved as a separate post which can get updated any time the user received more likes on their current version of their post than their most liked version.

I came up with a structure but I am pretty inexperienced with NoSQL database. Does this structure look like it will support my system? Also are these any glaring problems that will prevent important queries?

USERS (collection)
    DocumentID - userId gathered from Authentication uid
        firstName: String
        lastName:  String
        username:  String
        birthdate: Timestamp
        accountCreationDate: Timestamp
        post: postId (when user is created, create a default post document for them since there is only one post per user)
        bestPost:    postId
        FRIENDS (subcollection)
            DocumentID - userId of the friend
                username:  String

POSTS (collection)
    DocumentID - postId randomly generated
        authorUserId:   String
        authorUsername: String
        text:  String   
        imagePath: String
        location:  String
        likesCount: Number
        LIKES (subcollection)
            DocumentID - userID of the liker
                username:  String

The friends subcollection stores the friends username so creating a list of that user's friends by username is easy. I'm assuming I could then get more information of that user's friends by matching the documentID of a friend to the documentID in users.

Similarly for likes subcollection

1

1 Answers

2
votes

The structure looks okay. I would offer a few comments with regards to doing this in Cloud Firestore.

Updating likedCount

If the post likes are likely to be infrequent (less than one per second), you can create a Cloud Function (triggered by a likes sub-collection .onCreate) which updates the likesCount using a transaction. Make sure that the user cannot edit likesCount, within your rules.

Allowing the user to edit the most liked post

You'll need to build rules to enforce this. This could be a little more complex and may require some strategic thinking (unless you already have a solution).