I have a Firestore database with the following rule:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null && request.auth.uid == resource.data.uid;
allow create: if request.auth != null && request.auth.uid == request.resource.data.uid;
}
}
}
When querying for a set of documents, I need to include the uid
in the query to satisfy the rule and it works:
try await db.collection("Stocks")
.whereField("uid", isEqualTo: user.uid) // Include the uid for passing the rule
.getDocuments()
However, for a single document query for a document that doesn't exist in the database, it returns permission error:
let document = try await db.collection("Stocks")
.document(stock.id) // The document does not exist in the database
.getDocument()
if document.exists {
} else {
}
How can I define the rule for this case?
Rule for single document should be:
allow read: if request.auth != null &&
(request.auth.uid == resource.data.uid
|| !exists(/databases/$(database)/documents/$(document)));
It allow to read when the document doesn't exit in the database.