Issue
I'm looking to build a simple chat app using Flutter + Firestore, storing users and chats in separate collections. Each chat document has two string fields [uid1, uid2] representing the user ids of the respective participants. I need to be able to search for all chats for a given user (uid) so some type of OR query, this would be possible by storing them in an array field and using array_contains.
However, to update a chat document, I need to be able to query on both fields directly to retrieve a specific chat between two users, which would not be possible using the array approach (nested array_contains are not allowed). Even storing both as two top-level string fields requires two firestore queries for either direction.
Appreciate any advice on how to solve this limitation of Firestore queries?
Solution
You can create a composite field that contains all the data you need for the query by concatenating both user IDs into a single string. Be sure to sort the IDs before doing so, in order to ensure that they have a predictable order.
So, if you have user "A" and user "B", your composite field value would be simply "AB" (and never "BA"), and you can filter on this field to find all message between these two users.
Answered By - Doug Stevenson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.