BillyParadise
BillyParadise

Reputation: 105

Flutter firebase query, filter based on subcollection presence

I am trying to build a Firestore query in flutter which filters restaurant results based on the cuisine requested.

Based on the answer from Firestore query where map contains string by Lucas Aschenbach, I have designed my database so that the cuisines are listed in a common sub-collection

data model

and my query is:

final Query locations = FirebaseFirestore.instance
        .collection('locations')     
        .where('cuisines.$id.exists', isEqualTo: true);

I have added read access to the sub-collection:

match /locations/{l} {
      allow read: if true;
      allow write: if request.auth.token.role == 'admin';
    }
match /locations/{l}/cuisines {
      allow read: if true;
      allow write: if request.auth.token.role == 'admin';
    }

The $id in my test case is "american"

...but... no results.

Does anyone see anything obviously wrong? Appreciated!

Upvotes: 1

Views: 790

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600130

Queries on Cloud Firestore operate on a single collection, or a group of collections with the same name. There is no way to have a condition (or otherwise read) data from another collection in a query.

This means you .where('cuisines.$id.exists', isEqualTo: true) can only work if cuisines.$id.exists is present in the restaurant document. The most common way to implement your use-case is to add an array-field servedCuisines to the restaurant document, with the contents being the cuisines the restaurant serves.

`servedCuisines: ["american"]`

You then use an arrayContains operation in the query:

final Query locations = FirebaseFirestore.instance
        .collection('locations')     
        .where("cuisinesServed", arrayContains: id);

Upvotes: 1

Related Questions