skip to Main Content

In the Flutter app, I’m trying to retrieve data stored in a Firestore subcollection using this method.

 Stream<List<DocumentSnapshot<Object?>>> fetchNearbyData({
    required LatLng location,
  }) {
    final collectionReference = FirebaseFirestore.instance
        .collectionGroup(`postData`);
    return GeoFlutterFire()
        .collection(collectionRef: collectionReference)
        .within(
          center: GeoFlutterFire().point(
            latitude: location.latitude,
            longitude: location.longitude,
          ),
          radius: 10,
          field: `location`,
        );
  }

However, an error like this is being generated, and I cannot retrieve the data.

W/Firestore( 4280): (24.8.1) [Firestore]: Listen for Query(target=Query( collectionGroup=postData order by location.geohash, __name__);limitType=LIMIT_TO_FIRST) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}
I/flutter ( 4280): ----------------FIREBASE CRASHLYTICS----------------
I/flutter ( 4280): [cloud_firestore/permission-denied] The caller does not have permission to execute the specified operation.
I/flutter ( 4280): #0      EventChannelExtension.receiveGuardedBroadcastStream
exception.dart:67
I/flutter ( 4280): #1      MethodChannelQuery.snapshots.<anonymous closure>

I believe there might be an issue with the Firestore ‘Rules,’ and they are set as follows:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /user/{userId} {
      allow read, write: if true;
      match /{path=**}/postData/{postDataId} {
        allow read, write: if true;
      }
    }
  }
}

How can I retrieve data from the collection group?

2

Answers


  1. add this rule

        rules_version = '2';service cloud.firestore {
      match /databases/{database}/documents {
        match /user/{userId} {
          allow read, write: if true;
          match /{path=**}/postData/{postDataId} {
            allow read: if true;
          }
        }
      }
    }
    
    Login or Signup to reply.
  2. Since a collection group query reads from all collections with a specific name across the entire database, you need to grant the user permission to all collections of that name across the entire database. But the rules in your question only grant permission to the postData collections that are under user documents, which isn’t good enough.

    Move the permission for /{path=**}/postData/ to be a sibling match for the user path:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /user/{userId} {
          allow read, write: if true;
        }
        match /{path=**}/postData/{postDataId} {
          allow read, write: if true;
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search