I have a nested structure in my Firebase and I’m trying to get the CollectionGroup of guides with specific name.
Structure looks like this:
DOCUMENT: { dives : [ {guide: { firstName: 'Jhonny' } } ] }
Image with the structure of my database is attached:
My code is below:
const customerActivitiesQuery = query(collectionGroup(db, 'activities'),
where('dives', 'array-contains', { guide: { firstName: 'Johnny' } }))
Is there any chance to do this, or it is completely not possible with Firebase and I have to change the structure of my base?
>Solution :
The array-contains operator perform an exact equality check. So if your dives array contains an object that is exactly {guide: { firstName: 'Jhonny' } }, the operation will work.
The tricky bit here is that the equality check is performed on the binary gRPC data, which means that on that level it has to be the exact same value. But if they are indeed the same, the array-contains operation will work.
The more common case is that you have a subset of the fields in the array, and the array-contains operator is not made for that case.
The common workaround for that is to create an additional field with just the values you want to query on. For example:
dives_guide_firstnames: ["Jhonny"]
With that additional field, you can then query:
where('dives_guide_firstnames', 'array-contains', 'Johnny')
Note: you have a typo in Jhonny in the data structure, but I’m going to assume that is a typo in the question and not in the actual data.