skip to Main Content

Here’s what I’ve written;

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /reservedUsernames/{username} {
      allow update: if false;
      allow create: if request.auth != null;
    }
  }
}

I already added a document with ID sam and a field userId = 122. If I run an update on that document, see how below, it succeeds! How can I allow creations but no updates?

db.collection("reservedUsernames")
  .document(searchableUsername)
  .setData(["userId": userId])

2

Answers


  1. Chosen as BEST ANSWER

    I managed to do it by using Security Rules:

    rules_version = '2'
    
    service cloud.firestore {
      match /databases/{database}/documents {
        match /reservedUsernames/{documentId} {
          allow create: if request.auth != null && existingData(resource) == null
        }
    
        function incomingData(request) {
          return request == null || request.resource == null || request.resource.data == null ? null : request.resource.data
        }
    
        function existingData(resource) {
          return resource == null ? null : resource.data
        }
      }
    }
    

    This way I check if I'm updating an existing document and it passes only if I'm not!


  2. When using:

    .setData(["userId": userId])
    

    It means that you’re setting the data, and not updating it. The following rule:

    allow update: if false;
    

    Indeed rejects all update operations but as @DougStevenson mentioned in his comment, having it in your rules it’s the exact same thing as not having it at all, because by default the rules are set to false.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search