React Native Firebase Array Query to do ArrayContains with AND operation

Tags: , , , ,



I have group collection. In each group document, I store which users are associated with the group via members array field in firebase.

Eg: user1 & user2 are in xyz(id) group and I would like to query from client to get all the group where having user1 & user2 ( not OR ). I have tried firebase IN array query but it returns empty results. Is there is a way to query using AND, I am making chat application with react native.

My Code (Not Working:)

firestoreRef.collection('group').where('members','in',[ id_of_user1, id_of_user2 ]).get(); // return empty array

Answer

To begin with, with the current firebase capability, what you want to do is impossible. I’m sure you have read it already, but here is the documentation of firestore’s array related queries, and none of them support AND operation.

With that being said, it is a bit of a hack, but I have done something similar to what you want to do.

You would make a field that combines all of the users’ uids in single string, and you query with that field.

For example, let’s say you have the following two users:

user1
uid: 'abc'

user2
uid: 'def'

Then in their group document, you create a field, let’s call this memberKey for now and store their combined user ids as a single string:

{
  'memberKey': 'abcdef'
}

Now you can query the group at which user1 and user2 are in by combining their uids on the client to get the target document.

But there is one problem here. How do you know which uid comes first? How do you know it’s ‘abcdef’ and not ‘defabc’? Well, that easy. You just have to sort the list of uids alphanumerically. This way, you will always have consistent memberKey.

You can even expand this method to more than 2 users too.

I know this is not a very pretty solution that you were hoping for, but with firestore’s current limitation, we are forced to get clever like this.



Source: stackoverflow