Reading data from Firestore database on Web app

32 Views Asked by At

I am so very lost on how to simply read records from Firestore.

I have a single collection called properties. In it, I have several documents all in the same form (all have name, and category). That's it; no subcollections or anything complex.

I have set the rules as follows (many matches for testing):

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    allow read;
    
    match /{document=**} {
        allow read;
    }
  
    match /properties/{document=**} {
        allow read;
    }
    
    match /properties/{propertyid} {
        allow read;
    }
  }
}

Then, I have my web-based Expo app with the firebase npmjs package installed. I have initialized my Firebase app, and called getFirestore to grab a database instance and all called signInWithEmailAndPassword and signed in with a test account I set up in the Firebase console.

Finally, I want to grab all documents from the properties collection and display them on screen, so I wrote the following:

const query = collection(db, "properties");
const data = await getDocs(query);

I've also tried getting a specific property (I copied the ID from the Firebase console, so I know it exists):

const query = doc(db, "properties", "9sRm1TLWAIpYiZLfWPvo");
 const snapshot = await getDoc(query);

I am also doing the following:

  1. Printing out the user credentials that I called signInWithEmailAndPassword. I see a large object with my uid, accessToken, etc.
  2. Printing out my db variable (comes from this.db = getFirestore(this.app);). I see the correct information: firebase start options (apiKey, authDomain, projectId), my authentication credentials (current user uid matches what I see in the previous auth log, my auth object is filled out, etc. etc. (everything looks normal)

However, whatever the heck I try, I also get "Missing or insufficient permissions".

I've also checked my rules with the "Rules Playground" on any document under /properties and get successful simulated reads, both unauthenticated and authenticated.

What am I doing wrong and how can I just get a list of all documents in that collection? That's literally all I'm trying to do.

1

There are 1 best solutions below

2
Brusooo On
rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow read access to all documents
    match /{document=**} {
      allow read;
    }
  }
}

With these rules, you're allowing read access to all documents within the Firestore database. So there won't be any need in specifying properties path in rules. Try this one and check.