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

前端 未结 4 1266
-上瘾入骨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 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() {
    @Override
    public void onComplete(@NonNull Task doc) {
         if(!doc.getResult().exists()){
            //add new user
        }
    }                       
    

    }

    Rules:

    match /UsersProfile/{document=**} {
      allow read, write: if request.auth != null;
    }
    

提交回复
热议问题