I'm trying to prevent duplicate entries using Google Firestore rules, however it's not working. The rule I'm trying is:
service cloud.firestore {
// Prevent duplicate messages
match /databases/{database}/documents {
match /messages/{message} {
allow read;
allow write: if request.resource.data.m != resource.data.m;
}
}
}
From what I read, this should work.
What am I doing wrong?
To set up and deploy your first set of rules, open the Rules tab in the Cloud Firestore section of the Firebase console. Write your rules in the online editor, then click Publish.
You can use Firestore queries to get the document ID which corresponds to the field you want to keep unique. If the query returns null , that would mean that the database doesn't contain that value., ergo, the username , in this case, is available or vice versa.
Edit and update your rulesOpen the Firebase console and select your project. Then, select Realtime Database, Cloud Firestore or Storage from the product navigation, then click Rules to navigate to the Rules editor. Edit your rules directly in the editor.
Your rule if request.resource.data.m != resource.data.m
says that field m
can only be written if it's not the same as the current value of field m
in the same document.
There is no way to check for duplicates in the entire collection in security rules, as that would require Cloud Firestore to read all documents in the collection (which would become very expensive at scale).
The only way to currently implement a uniqueness constraint is by create a separate collection where you use m
as the document IDs. Since document IDs in a collection are by definition unique, you can enforce the rule there with:
match /unique_ms/{m} {
allow create;
}
The above only allows creating a document, it does not allow updating it. This means that once someone created a document with a specific value of m
, nobody can overwrite it.
An alternative using the write
rule could be:
allow write: if !exists(/databases/$(database)/documents/unique_ms/{m});
Also see:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With