【问题标题】:Firestore - order documents by document field in subcollectionFirestore - 按子集合中的文档字段排序文档
【发布时间】:2019-11-03 21:16:58
【问题描述】:

我有一个 Flutter 应用,用户可以在其中使用 Firestore RTDB 互相租用物品。 rental 文档有一个 chat 集合,用于存储两个用户之间的聊天记录:

rentals (collection)
    rental_1 (document)
        chat (collection)
            message_timestamp_1 (document)
            message_timestamp_2 (document)
        users (array, document field)
            user_id_1 (String)
            user_id_2 (String)
    rental_2 (document)
        chat (collection)
            message_timestamp_1 (document)
        etc.

我的应用中有一个页面,它是用户参与的所有租赁的列表视图(users 字段上的简单arrayContains)。基本上,我想显示用户参与的所有聊天。但是,我想按最近的聊天排序这个列表(就像任何普通的消息传递应用程序一样)。有没有一种方法可以实现这一点,而不必在rental 文档中存储和更新lastUpdated 字段(从而在每次发送消息时创建两次写入)?

【问题讨论】:

    标签: flutter google-cloud-firestore


    【解决方案1】:

    rental 文档中添加lastUpdated 字段,并使用array-containslastUpdated 字段排序来查询用户参与的最新租赁文档将解决您的问题。正如您所提到的,这将花费您每条消息的两次写入,并且可能导致计费陷阱,因为chats 子集合中可能会出现大量消息。

    或者,您可以将 chats 集合创建为具有字段 rentalId 的顶级集合,以便您可以查询此顶级集合以显示用户最近参与的租赁聊天。这将消除将单个消息写入 Firestore 时必须执行的两次写入。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 2022-09-27
      • 2021-07-29
      相关资源
      最近更新 更多