Reputation: 193
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?
Upvotes: 5
Views: 7744
Reputation: 2501
I'm using whereEqualsTo but you can use any query:
FirebaseFirestore db = FirebaseFirestore.getInstance();
Query docRef = db.collection("rewards").whereEqualTo("adminId", Common.currentUser.getContact());
docRef.addSnapshotListener((value, error) -> {
if (value.getDocuments().size() == 0) {
Snackbar snackbar = Snackbar.make(findViewById(R.id.content), "Empty", Snackbar.LENGTH_LONG);
snackbar.show();
}
It works for me
Upvotes: 0
Reputation: 2715
In order to check if the Document incoming
is empty, you can check for the number of keys of the stored object. If there are 0 keys stored, you can then delete the document.
Example code in Typescript:
const doc = await firestore()
.collection('Collection')
.doc('incoming')
.get();
const numberOfKeys = Object.keys(doc.data()).length;
if (numberOfKeys === 0) {
await firestore()
.collection('Collection')
.doc('incoming')
.delete();
Upvotes: 4
Reputation: 138824
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.
Upvotes: 3