I rearranged the security rules for cloud firestore to prevent the recreation of a document in a collection. Here is the rules I used :
match /UserData/{uid}/DAILY_USAGES/{day} {
allow create: if !exists(/databases/$(database)/documents/UserData/$(request.auth.uid)/DAILY_USAGES/$(day));
allow read, update: if request.auth.uid == uid;
}
I simulated this rules in console with these document path and user credentials
/UserData/UoeJtUhPpJTi78HouKLIqhcRpfs48/DAILY_USAGES/09-07-2020
If I create a document with the id 09-07-2020 and simulate with above path, it fails. When I delete the document 09-07-2020 then above simulation it works. So it works well in rules simulator.
But when I try in the app, every time when I try it creates the document again. So if the document content was different before, it is resetting to default value that I used to create document.
Here is the code I used in android studio to create this document only once
DailyUsage usage = new DailyUsage();
usage.setUsage(0);
usage.setTime(formatDate(date));
FirebaseFirestore.getInstance().collection(Constants.USER_DATA_ROOT).document(uid)
.collection(Constants.FIRESTORE_CHILD_DAILY_USAGES).document(today).set(usage);
I don't want to check that if document exists before, because it slows the ui and not works as I expect. So I tried to use the security rules to prevent recreation of documents but not working on application. Can anyone help for this ?