Evan
Evan

Reputation: 880

Firestore - order documents by document field in subcollection

I have a Flutter app where users can rent items from each other with Firestore RTDB. rental documents have a chat collection that stores the chats between two users:

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.

I have a page in my app that is a listview of all the rentals that the user is involved in (simple arrayContains on the users field). Basically, I want to show all the chats the user is involved in. However, I would like to order this list by most recent chat (like any normal messaging app). Is there a way to achieve this without having to store and update a lastUpdated field in the rental document (thus creating two writes each time a message is sent)?

Upvotes: 0

Views: 87

Answers (1)

denniskbijo
denniskbijo

Reputation: 576

Adding that lastUpdated field in the rental document and querying the latest rental documents in which a user is involved using array-contains and ordering by lastUpdated field will solve your problem. As you have mentioned this will cost you two writes per message and can lead to a billing trap as a lot of messages can be expected in the chats sub-collection.

Alternatively you can create the chats collection as a top-level collection with a field rentalId so that you can query on this top-level collection to show the recent rental chats the user is involved in. This will eliminate the two writes you have to perform when writing a single message to the firestore.

Hope that helps.

Upvotes: 0

Related Questions