Can someone demonstrate how to use the count()
function in a Firestore Security Rules to limit the number of documents created?
This is my current code, but it is now working:
match /doc/{docId}{
allow read: if resource.data.publicAccess == true ||
(request.auth != null && request.auth.uid == resource.data.createdBy) ;
allow write: if request.auth != null && request.auth.uid == resource.data.createdBy ;
allow create: if request.auth != null && request.auth.uid == request.resource.data.createdBy &&
get(/databases/$(database)/documents/doc).where("createdBy", "==", request.auth.uid).count() < 10;
}
There is no way you can perform a query within Firestore Security Rules. What you can do is to read a single document that exists at a known path that you know ahead of time. Firestore Security Rules only provide access control and data validation, nothing more. Please also note that the COUNT()
operation is also a query called an aggregation query, so there is also no way you can do that.
The single option that you have is to maintain your own counter in a separate document that can be read inside the Firestore Security Rules and perform the necessary checks against it.
As @FrankvanPuffelen mentioned in his comment, you can get useful information from this answer, but since everything in Firestore it's about the number of reads and writes you perform, I recommend you save the counter in the Realtime Database, where the write operation is free of charge.