Issue
In my TimeForm
activity I add some data to Firestore but I don't add them in specific documents because I need to read them all using .addSnapshotListener
But I need to delete some of the documents. For example here are my documents in the Monday collection:
But when I tried to delete them doing this:
db.collection("monday").document()
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
It doesn't work because I haven't set the document name. Then I asked how to get a documents id(here is the page: Delete data from firestore) it didn't send the correct document id. I added a test button and when I clicked it, it displayed a toast with the document's id but everytime I pressed it, it displayed random ids and none of them were correct. How can I delete those documents one by one of all of them at once.
Solution
it displayed random ids and none of them were correct.
This is happening because you aren't passing anything to the document()
method. According to the official documentation of CollectionReference's document() method:
Returns a DocumentReference pointing to a new document with an auto-generated ID within this collection.
So everytime you call document()
method without passing any argument, you get a new auto-generated ID
which will never match with one of your existing one.
In order to delete a particular document, you need to pass the particular id of the document that you want to delete to the document()
method. It might look something like this:
db.collection("monday").document("2wZg ... GmfS").delete().addOnSuccessListener(/* ... */);
Answered By - Alex Mamo
Answer Checked By - Robin (JavaFixing Admin)