Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent duplicate entries in Firestore rules not working

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.

enter image description here

What am I doing wrong?

like image 394
Maarten Raaijmakers Avatar asked Jan 17 '19 12:01

Maarten Raaijmakers


People also ask

How do I set firestore database rules?

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.

How do you make a field unique in firestore?

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.

How do you update firestore rules?

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.


1 Answers

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:

  • Cloud Firestore: Enforcing Unique User Names
  • firebase rule for unique property in firestore
like image 60
Frank van Puffelen Avatar answered Sep 20 '22 14:09

Frank van Puffelen