How to check if Cloud Firestore collection exists? ( querysnapshot)

前端 未结 2 993
盖世英雄少女心
盖世英雄少女心 2021-01-21 17:37

I\'m having trouble with checking if my collections exists in Firestore database. When I was working with Firebase Realtime database i could have used:

if(databa         


        
2条回答
  •  遇见更好的自我
    2021-01-21 17:57

    Use DocumentSnapshot.size() > 0 to check if the collection exists or not.

    Here is an example from my code:

      db.collection("rooms").whereEqualTo("pairId",finalpairs)
             .get()
             .addOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete(@NonNull Task task) {
                if (task.isSuccessful()) {
                    if(task.getResult().size() > 0) {
                        for (DocumentSnapshot document : task.getResult()) {
                            Log.d(FTAG, "Room already exists, start the chat");
    
                        }
                    } else {
                        Log.d(FTAG, "room doesn't exist create a new room");
    
                    }
                } else {
                    Log.d(FTAG, "Error getting documents: ", task.getException());
                }
            }
        });
    

提交回复
热议问题