1
votes

My database is structured with a users collection and a messages collection (seen below). There will only be 1-2-1 messaging in the app (no chat rooms).The messages collection's documents are named as user1:user2.

I'm trying to create a page in my app where a user can see all the users they have chats with and then can click on each of those chats and open up the message chain with that user. I'm confident I know how to create the second part of this (the message chain) but I'm not sure how to pull back all of the current chats a user has.

So far I've got

    def load_chats(self):
        messages = self.my_firestore.db.collection(u'messages').stream()
        #self.users = self.my_firestore.db.collection(u'users').stream()
        for doc in messages:
            if self.local_id in doc.id: #This is checking if "user1" is in "user1:user2", for example
                chat_messages.add_widget(ChatButton) #Adds a new button each time it finds "user1" in the doc.id within messages

In this for loop, when I'm creating the button for the chats I need information from the users collection so I can display the name of the person the chat is with.

However, I'm not sure how to do this - beyond putting a for loop within for doc in messages which cycles through self.users and returns the user information if it matches "user2". This would create a huge number of reads so I'm not even entertaining my crazy idea!

messages collection

messages collection continued

users collection

Any help would be much appreciated, let me know if it's not clear.

1

1 Answers

0
votes

You could add a Participants array field to your chat groups:

data = {
    'GroupId': 'userOneID:userTwoID',
    'Participants': ['userOneID', 'userTwoID']
}

Then you could query for chat groups where a user is either userOne or userTwo in a chat group:

chatGroups = self.my_firestore.db.collection(u'messages') \
                 .where('Participants', 'array_contains', 'userID') \
                 .stream()