Create a document only if it doesn't exist in Firebase Firestore

前端 未结 4 1267
-上瘾入骨i
-上瘾入骨i 2021-02-14 19:30

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.

The app flow:

  1. Create a
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-14 19:41

    If you want to allow creating a document only if it doesn't already exist, just use the allow create rule that you already have. Because you also have an allow update rule, updating the existing data is also allowed.

    The following rules should be sufficient:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{uid} {
          allow create: if request.auth != null && request.auth.uid == uid;
        }
      }
    } 
    

    You don't need the exists() call, because allow create only applies if the data does not exist.

    Now to your question: You should clarify what you mean exactly. Now only the authenticated user can modify its own record. If you don't want to allow arbitrary data to be written, check for it.

    Here are some examples: https://firebase.google.com/docs/firestore/security/rules-conditions#authentication

提交回复
热议问题