Search code examples
google-cloud-firestorefirebase-security

Exists not working in Firebase Security Rules


I'm using the firestore emulator and exists isn't preventing calls when the document exists.

match /usernames/{username} {
  allow update: if false;
  allow create: if isUsernameAvailable(request.resource.data.username);

  function isUsernameAvailable(rawName) {
      let name = rawName.lower();

      return isValidMessage() &&
             isValidUsername(name) &&
             !exists(/databases/$(database)/documents/users/$(request.auth.uid));
  }

Here is the accepted Request: Request

and Pre-Existing Document:

Pre-Existing Document

The document clearly exists. I've compared my code to similar code, and I don't see syntactical errors, so I'm at a loss.


Solution

  • The document title in the bottom right of that second screenshot is shown in italics, which means that the document does not actually exist. The ID is just shown in the Firestore console because you have subcollections with data under it.

    In the fields section of the console, you'll also find a message to explain this:

    This document does not exist, it will not appear in queries or snapshots. Learn more

    And since the document doesn't actually exist, calling exist on that path correctly returns false. If you want it to return true, you'll have to ensure that the document actually exists.

    Also see: