skip to Main Content

I am trying to query a cloud firestore database and i need it to return all the documents in the chats collection sorted by the timestamp field which is a field that all the documents in the messages sub-collection have.

i tried writing a query like this.

FirebaseFirestore.instance.collection("chats").orderBy("messages.timestamp", descending: true)].get(),

but it does not return any documents when actually there are some documents there.

2

Answers


  1. Firestore can only order or filter on data in the documents that it returns. There is no ability to order or filter on data outside of those documents.

    So if we want to order chats in the timestamp of the last message in that chat (a common use-case), you’ll have to include a lastMessageTimestamp field in the chat document itself, and update that whenever a message is written in its messages subcollection. With that lastMessageTimestamp field in place in each chats document, you can then order and filter on that.

    Login or Signup to reply.
  2. Create a new collection called messages and store all messages for every user there (with a user id field). Reference the message uid’s via an array in each chat. This way you can easily query for the messages associated with a chat session then sort them.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search