title: Create a document only if it doesn't exist in Firebase Firestore
body: <p>What I am trying to achieve is very simple. I need to create a user entry in the database only if it doesn't exist.</p>
  <p><strong>The app flow:</strong></p>
  <ol>
  <li>Create a user with Firebase Auth (obtain UID)</li>
  <li>Create a user document in the database using UID as the key</li>
  </ol>
  <p><strong>The client code (create operation):</strong></p>
  <pre><code>this.db.doc('users/' + uid).set({username: Santa})
  </code></pre>
  <p><strong>The firestore rules:</strong></p>
  <pre><code>service cloud.firestore {
    match /databases/{database}/documents {
      match /users/{uid} {
        allow create: if 
          request.auth != null &amp;&amp; 
          request.auth.uid == uid &amp;&amp; 
          !exists(/databases/$(database)/documents/users/$(uid));
        allow update: if request.auth != null &amp;&amp; request.auth.uid == uid; 
      }
    }
  } 
  </code></pre>
  <p><strong>Additional info:</strong></p>
  <p>As you may already know the code doesn't work. Everytime I run the client-side code the current user is completely replaced with a new document. However, if I delete the following line from the rules everything works as expected:</p>
  <pre><code>allow update: if request.auth != null &amp;&amp; request.auth.uid == uid;
  </code></pre>
  <p>But now the question arises, how do I secure data inside user document from unauthorised modifications? Any advice?</p>