Home > database >  Firestore social media friend requests data model
Firestore social media friend requests data model

Time:09-14

I am using Firestore to build a social media, I am wondering what is the best way to structure the data for friend requests is.

When a user John wants to friend request Mary and Anne, Do I create a root collection called friend_requests and add 3 documents:

  1. A document with John’s userId as a key the value of which will be an object each for both Mary and Anne’s containing their userId and the status of request (pending/accepted/declined)
  2. A document with Mary’s userId as a key and an array with object with John's userId and status of request
  3. A document with Annes’s userId as a key and an array with object with John's userId and status of request

Now, when Anne and Mary accept the friend request, I delete all three documents in friend_requests collection and then:

  • I add a sub collection for each user (in users root collection) called friends that contains usersIds, displayNames and photoURLs of friends that have accepted requests

or

  • Should I make another root collection friends that has a document for each user containing the friends information instead?

It seems like a lot of duplicate data so im trying to wrap my head around it and find the best and most efficient way to do it in firestore. Any advice would be much appreciated and maybe I am going about it the wrong way!

CodePudding user response:

The first approach seems to have a lot of document creations and deletions. Instead you could create a sub-collection "friends" under "users" and store a field "status". So the structure would be:

users -> {userId} -> friends -> {friendId}

When User2 sends a friend request to User1, you can add a friend sub-document under User1 and set the status field to requested along with friendId. Once User1 accepts the request, just update the status to active. This will reduce costs of that 1 delete and 1 create operations per friend request.

This should cover many use cases including:

  1. Listing friends/friend request of a users
  2. Listing pending friend requests sent by me (a collection group query can be used if you use sub-collection)

You can use Firestore triggers for Cloud Functions if you need to process anything like updating database, sending a notification/e-mail, etc when the friend request has been accepted.


The friends sub-collection could be a root-level collection but in that case you'll have to add another field userId to filter of friends of a given user. That doesn't make a big difference but checkout What are the benefits of using a root collection in Firestore vs. a subcollection? for more information on that.

  • Related