0

Given the following problem:

A user has a set of chats and they have a set of messages.

I want to get chat messages sorted by date and also be able to paginate them.

At the moment my structure has the following form:

-chatCollection
    -chatID
        -properties
        ...


-userChatCollection
    -userID
        -chatID


-chatMessagesCollection
    -chatID
        -messageUID
           -date:""

As a programmer who has used SQL I would say that the answer is simple: Through the user I can obtain the chats and through the chats I can obtain the ordered messages and limit them.

But as they say from firebase: Do not try to emulate a SQL query in firebase but try to store your data so that they will be easy to retrieve, I do not know if this structure is appropriate for my problem.

Could it be a solution to create a separate collection with only the order of the messages?

Rafa Amo
  • 76
  • 6
  • We are usually structuring a Firestore database according to the queries that we want to perform. What are those queries? – Alex Mamo Apr 17 '20 at 10:48
  • I would like to consult the messages of a chat (through the id), ordered by date and limited. – Rafa Amo Apr 17 '20 at 10:56
  • I would recommend you add your database structure as a screenshot, to see it more clearly. Besides that, here you can find an [alternative database structure](https://www.youtube.com/watch?v=u3KwKQddPoo&list=PLn2n4GESV0Ak1HiH0tTPTJXsOEy-5v9qb&index=3) that can help you with a hint. – Alex Mamo Apr 17 '20 at 11:22
  • @AlexMamo I have seen your structure and my question is: How can you sort your messages by date and at the same time paginate them? – Rafa Amo Apr 17 '20 at 13:18
  • Calling an `orderBy()` method on the query and to paginate, check [this answer](https://stackoverflow.com/questions/50741958/how-to-paginate-firestore-with-android) or [this article](https://medium.com/firebase-tips-tricks/how-to-create-a-clean-firestore-pagination-with-real-time-updates-ce05a87bb902) if you need **real-time** pagination. – Alex Mamo Apr 17 '20 at 13:24
  • So I am seeing my main problem is that to paginate my data I need to sort by **__name__** and along with sorting by **date**, firebase throws an exception: **The query requires an index.** So if I create a composite index maybe I can do what I'm looking for – Rafa Amo Apr 17 '20 at 13:44
  • Yes, check **[this](https://stackoverflow.com/questions/50305328/firestore-whereequalto-orderby-and-limit1-not-working)** out. – Alex Mamo Apr 17 '20 at 13:46
  • 1
    Yes, yes and yes I think I can do what I'm looking for. Thank's @AlexMamo – Rafa Amo Apr 17 '20 at 13:56

0 Answers0