In Cloud Firestore how to make an, create only once security rule

Viewed 1020

I just stared migrate to Cloud Firestore and wonder about this security rule. In the Firebase realtime databas this rule:

Evaluates to true if one operand in the rules expression is true.

In this example, we can write as long as old data or new data does not exist. In other words, we can write if we're deleting or creating data, but not updating data.

".write": "!data.exists() || !newData.exists()"

I´m trying to replicate in the Cloud Firestore like

match /USER_ID/{Id} {
  allow create: if resource.data.id != exist
  allow read: if request.auth.uid != null;
  }

What I want is that if the Document exist in the USER_ID Collection then the Transaction this is happening in must fail. But this is not working. I have read the doc a few times but cant get it to work

1 Answers

You'll want to use the exist function, for which you need to pass it the path of the document you are testing if it exists. Below is an example of how you'd check if the document doesn't exist.

service cloud.firestore {
   match /databases/{database}/documents/ {
      match /USER_ID/{Id} {
         allow create: if !exists(/databases/$(database)/documents/USER_ID/$(Id))
         allow read: if request.auth.uid != null;
      }
   }
}
Related