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?


Solution 1:

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