【问题标题】:Getting information from one users collection when cycling through messages collection - Firestore循环浏览消息集合时从一个用户集合中获取信息 - Firestore
【发布时间】:2020-12-13 12:28:16
【问题描述】:

我的数据库由用户集合和消息集合构成(见下文)。应用中只有 1-2-1 消息(没有聊天室)。消息集合的文档命名为 user1:user2。

我正在尝试在我的应用程序中创建一个页面,用户可以在其中查看他们与之聊天的所有用户,然后可以单击每个聊天并打开与该用户的消息链。我确信我知道如何创建第二部分(消息链),但我不确定如何撤回用户当前的所有聊天记录。

目前为止

    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

在这个 for 循环中,当我为聊天创建按钮时,我需要来自 users 集合的信息,以便显示与之聊天的人的姓名。

但是,我不确定如何执行此操作 - 除了在 for doc in messages 中放置一个 for 循环,该循环循环通过 self.users 并在匹配“user2”时返回用户信息。这会产生大量的阅读量,所以我什至不会接受我的疯狂想法!

任何帮助将不胜感激,如果不清楚,请告诉我。

【问题讨论】:

    标签: python google-cloud-firestore


    【解决方案1】:

    您可以将Participants 数组字段添加到您的聊天组:

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

    然后您可以查询聊天组中用户为userOneuserTwo 的聊天组:

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

    【讨论】:

    • 谢谢,这会比这个解决方案使用更少的读取:def user_messages(self): messages = self.my_firestore.db.collection(u'messages').stream() user_messages = self.root.get_screen("user_messages").ids['user_messages_layout'] for doc in messages: if self.local_id in doc.id: user_id = doc.id.split(":")[1] user = self.my_firestore.db.collection(u'users').document(user_id).get() 我最初是这样创建的,但如果你的建议会使用更少的读取(或者通常更有效),我会改变你的说
    • 抱歉格式不好,我不确定如何在评论中正确添加代码
    • 是的,where 过滤器避免每次加载整个messages 集合。
    猜你喜欢
    • 1970-01-01
    • 2021-06-28
    • 2021-05-08
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多