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

前端 未结 4 1280
-上瘾入骨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

    0 讨论(0)
  • 2021-02-14 19:52

    I had use this and it worked. Basically I make sure the user is logged in by request.auth != null and then I check to see if the resource requested is null. If the resource already exists, then it means the user exists.

    I added in the allow update in case you wanted only the user to change their own data.

    match /users/{document} {
          allow create: if request.auth != null && resource == null;
          allow update: if request.auth != null && request.auth.uid == resource.data.author_uid;
    }
    
    0 讨论(0)
  • 2021-02-14 19:56

    this.db.doc('users/' + uid).set({username: Santa}, {merge: true}) It should merge and not replace. Fields omitted will remain untouched. https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference#set

    0 讨论(0)
  • 2021-02-14 20:04

    Use logic in your code, but not in rules. Add addOnCompleteListener to user collection and after get the result do some actions.

    getUsers.document(userUID).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> doc) {
         if(!doc.getResult().exists()){
            //add new user
        }
    }                       
    

    }

    Rules:

    match /UsersProfile/{document=**} {
      allow read, write: if request.auth != null;
    }
    
    0 讨论(0)
提交回复
热议问题