0

So what I'm trying to do is a chat app, but the problem is I don't know how to make a connection between two users. What I've done is that there's a users collection, inside that collection, there are some users that got a collection of friends that a user can add, so I managed to let the user enter the email of a friend and lookup for it in the users' collection, but I couldn't make a connection between the user and its friend to chat, I was thinking of making a chat collection for each user but I think this won't be efficient and still can't share the same collection between two users, any ideas how to structure it properly?

Thanks in advance for any help you are able to provide.

Yusuf Abdelaziz
  • 379
  • 3
  • 7
  • 1
    My typical solution is to create a collection for the 1:1 chat between two users by combining their UIDs. See my answer here: https://stackoverflow.com/questions/33540479/best-way-to-manage-chat-channels-in-firebase – Frank van Puffelen Jun 19 '20 at 14:48
  • I'm thankful to you, combining the user and the peer IDs is a magnificent idea. – Yusuf Abdelaziz Jun 27 '20 at 14:25

1 Answers1

1

These approaches are the basic for Firestore based chats

  • Messages Collection Approach: chats\{chatID}\messages\{messageID} using sub-collections but it requires a unique read for every message, every message is limited to 1MB.

  • Embedded Document Approach: chats\{chatID}.messages[] create a only one document per chat room, but this will hit the limit of 1MB per document

I recommend read the use case of this example in order to have more ideas for your implementation and how to deal with 1MB limit.

In the example is proposed to use joins for find the chat room but this will add complexity to the database, this answer in your question comments uses the following approach to generate and share the room ID.

Use the User IDs and merge them to generate the room ID, this approach could take advantage of the friend list to find and generate the room ID

This is the code proposed to generate the room ID

var chatID = 'chat_'+(user1<user2 ? user1+'_'+user2 : user2+'_'+user1);

Friendlist example:

{

    userid:"user1",
    "friendlist"{

    "user2":"chat_user1_user2" \\result of previous code
    }
}
Jan Hernandez
  • 4,414
  • 2
  • 12
  • 18