Juan Valenzuela
Juan Valenzuela

Reputation: 33

Can't access collection inside document with rules in firestore

I'm trying to get in my application a set of documents inside a collection like this:

const plans = await firebase.firestore()
                        .collection('users')
                        .doc(userId)
                        .collection('plans')
                        .get();

My firestore rules are set like this:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow create: if request.auth.uid != null;
      allow get: if request.auth.uid == userId;

      match /plans/{document=**}  {
        allow create, get, update, delete: if request.auth.uid == userId;
      }
    }
  }
}

Every time I try to query all documents in plans collection, I receive this error

FirebaseError: Missing or insufficient permissions

But if I try to query just the user doc

firebase.firestore().collection('users').doc(userId).get()

It works just fine. I've been stuck on this for a while. Am I missing something?

Upvotes: 0

Views: 837

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317392

The problem is that you're only allowing get for plans. get only allows individual document access. But a query that returns multiple documents requires list access (or read, which is both get and list combined).

Note that write is also a combination of create, update, and delete, so you can be more succinct like this:

      match /plans/{document=**}  {
        allow read, write: if request.auth.uid == userId;
      }

Read more about granular operations in the documentation.

Upvotes: 1

Related Questions