Home > OS >  How to query Firestore documents filtered by roles defined in a subcollection
How to query Firestore documents filtered by roles defined in a subcollection

Time:12-30

In the Security Rules! video #6 the suggestion is made to create a security rule using roles defined in a private_data sub collection with a single 'private' document:

allow update: if (get(/databases/$(database)/documents/restaurants/$(restaurantID)/private_data/private).data.roles[request.auth.uid] in ['editor', 'owner'];

Using the web API, how can I query the set of documents where a user has editor or owner permissions? I don't see that a where clause can reference sub-collection documents.

Something like

const q = query(
    collection(db, 'restaurants'),
    where(new FieldPath('private_data', 'private', 'roles', 'user_123'),  'in', ['editor', 'owner'])
  );

CodePudding user response:

Firestore queries can only filter documents based on the data in each document itself. There is no way to filter based on data in another document, either from the same collection or from another (sub)collection.

This means that while it is possible to restrict write and get (single-document read) operations based on the information in the roles subcollection, it is not possible to use those same documents in a query.

If you need this use-case, the common approach is to duplicate the necessary data from the subcollection(s) into the parent document, and the filter on it there. This complicating of data write to allow or simplify a certain read is a pattern you'll see quite regularly when dealing with NoSQL databases.

  • Related