Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for an empty document on Firestore?

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?

enter image description here

like image 962
Abhinav Prakash Avatar asked Jul 27 '18 11:07

Abhinav Prakash


People also ask

How do I add a blank document to firestore?

Set the data of a document within a collection, explicitly specifying a document identifier. Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier. Create an empty document with an automatically generated identifier, and assign data to it later.

How do you check data on firestore?

Cloud Firestore doesn't support native indexing or search for text fields in documents. Additionally, downloading an entire collection to search for fields client-side isn't practical. To enable full text search of your Cloud Firestore data, use a dedicated third-party search service.

How do I read a document on firestore?

Reading data from Firestore There are two ways for retrieving data, which is stored in Cloud Firestore. Calling a method to get the data. Setting a listener for receiving data changes events. We send an initial snapshot of the data, and then another snapshot is sent when the document changes.


1 Answers

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

yourDocumentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Map<String, Object> 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.

like image 62
Alex Mamo Avatar answered Sep 27 '22 23:09

Alex Mamo