0

So I have a collection of documents in cloud firestore where each document has this structure:

{
key1: value1
key2: value2
access: [{key: {key: value, key: value}, users: [...keys]},]
}

From a widget I want to get the documents where the id that I have exists in the users array. My query is this: labs.where('access.users', arrayContains: user.id).get() I have read that in order to query nested elements you need dot notation. My problem is that it results in an error -> Bad state: No element. Which I assume is, because firestore doesn't know which access.users to query on since it is a list, but on the other hand I imagine that it should take each map one by one.

Maybe I'm missing something in my logic. Help is appreciated.

Marios Koni
  • 143
  • 1
  • 13
  • 1
    Have you checked [Firestore to query by an array's field value](https://stackoverflow.com/q/54081799/13130697) ? This isn't possible unless you know the whole object. – Dharmaraj May 03 '22 at 10:50

1 Answers1

1

As Dharmaraj commented, the arrayContains operator checks whether the array contains an item that is exactly the same as you pass to it. There is no way to pass a partial object to arrayContains and check for the presence of just that part.

The common workaround is to create an additional array field that just contains the values you also want to query on. So in your case that'd be an array of the UIDs that have access:

access_users: ["uid1", "uid2", "uid3"]

And then your query would become:

labs.where('access_users', arrayContains: user.id).get() 
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807