How to check for an empty document on Firestore?

后端 未结 2 735
执念已碎
执念已碎 2020-12-21 01:19

So I am trying to delete a document on Firebase Firestore which contains no fields. But how can I check whether the document contains no data before I delete it

2条回答
  •  感动是毒
    2020-12-21 01:56

    To solve this, you should get the data from the database as a Map:

    yourDocumentReference.get().addOnCompleteListener(new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    Map map = document.getData();
                    if (map.size() == 0) {
                        Log.d(TAG, "Document is empty!");
                    } else {
                        Log.d(TAG, "Document is not empty!");
                    }
                }
            }
        }
    });
    

    To check a document only for existens it doesn't mean that is empty. The document can exist (like in your screenshot) but has no properties set. Because every document in a Cloud Firestore database is a Map, you can use size() method to see if is empty or not.

提交回复
热议问题