Deleting All Documents in Firestore Collection

Deleting all documents in Firestore collection

There is no API to delete an entire collection (or its contents) in one go.

From the Firestore documentation:

To delete an entire collection or subcollection in Cloud Firestore, retrieve all the documents within the collection or subcollection and delete them. If you have larger collections, you may want to delete the documents in smaller batches to avoid out-of-memory errors. Repeat the process until you've deleted the entire collection or subcollection.

There is even a Swift sample in that documentation, so I recommend you try it.

The Firebase CLI allows you to delete an entire collection with a single command, but it just calls the API to delete all documents in that collection in batches. If this suits your needs, I recommend you check out the (sparse) documentation for the firestore:delete command.

How to delete all the documents in a firestore collection database

The documentation is correct: you have to delete the documents individually. It's not impossible - you just have to query for all the documents first, then delete each one. For example:

db.collection('cities').get().then(querySnapshot => {
querySnapshot.docs.forEach(snapshot => {
snapshot.ref.delete();
})
})

To delete all documents from a firestore collection

The solution was to add a check-in as @Doug Stevenson suggested:

if(snapshot)

How to delete documents from Firestore from different collections

The Inspection documents are displayed in an italic font in the console: this means that these documents are only present as "containers" of the assignedToMe subcollection but that they are not "genuine" documents. See more info in this answer.

In addition, deleting a document does not delete the documents present in its subcollections, as also explained in the linked answer. You have to delete the subcollections documents as well.

More concretely, in your case, you need to loop over assignedToMe subcollection in order to delete all the documents it contains. You can group all the delete() operations in a Batched Write, as follows:

  router.use('/delete', [auth, admin], async function (req, res, next) {
try {
const { email } = req.body;
const userRef = db.collection('Users').doc(email);

const user = await userRef.get();

if (!user.exists) {
return res.status(404).send('This user has already been deleted!');
} else {
const batch = db.batch();

// Deleting the user doc
batch.delete(userRef);

// Deleting the assignedToMe subcollection docs
const assignedToMeRef = db
.collection('Inspection')
.doc(email)
.collection('assignedToMe');

const assignedToMeQuerySnapshot = await assignedToMeRef.get();

assignedToMeQuerySnapshot.forEach((doc) => {
batch.delete(doc.ref);
});
// Note that if the assignedToMe subcollection is empty
// nothing will be added to the batched write by the previous loop

await batch.commit();

result && res.status(200).send('User deleted successfully.');
}
} catch (error) {
console.log(error);
return res
.status(500)
.send('The following error occured: ' + JSON.stringify(error));
}
});

Note that a batched write can contain up to 500 operations. If you plan to have assignedToMe subcollections with more than 499 documents (the batched write also deletes the user doc), you would need to use Promise.all().

How to delete fields for all documents in Firestore

Bulks writes are not possible in Firestore at the moment and to update any document you need a reference to it i.e. the document ID. That means you would have to read all the documents, get a reference to them and update them.

// Reading all documents
const colRef = firebase.firestore().collection("users")
const colSnapshot = await colRef.get()

const delField = {first_name: firebase.firestore.FieldValue.delete()}

// Array of update promises
const updates = colSnapshot.docs.map((doc) => colRef.doc(doc.id).update(delField))
// Run the promises simulatneously
await Promise.all(updates)

It'll cost N reads and write where N is number of documents but this seems to be the only way. Unless you have array of document IDs somewhere else (it'll prevent reads as you already know the doc IDs).

Delete all documents in Firestore collection

Update:

After doing some research and read so many other answers on this site about this matter, I used this method and I think it is so simple for a dummy like me but never mentioned on other answers I am not sure why:

To remove a user completely from authentication, I used the Firestore extension called "Delete User Data" which is a great help, it is magical and allows me to remove a user just by using this code:

FirebaseAuth.getInstance().getCurrentUser().delete().addOnSuccessListener(new OnSuccessListener<Void>() {...}

It doesn't only delete user authentication, with just that code, that particular user's data in the firestore and the images in the storage are also gone. It is fantastic!
The important point is that you have to connect the user UID from the authentication and connects the UID to the firestore and the storage.

To know more about how to use the "Delete User Data" Firestore extension(it is still in beta mode), try looking at this great blog tutorial from JORGE VERGARA : Installing the Delete User Data extension

How I set the configuration of the extension to delete a user:
Sample Image

How to use the extension: It is so simple I am so happy that it helps me to delete a user so easily without fuss
Sample Image

This is the storage structure:
Sample Image

The structure of my Firestore:

main(collection)--->userID---->journal(collection)----->journalIDdsvsfbsf
----->journalIDdfvdbgnd
--->userID2--->journal(collection)----->journalIDdsvsfbsf
----->journalIDdfvdbgnd

Sample Image

The Authentication structure:
Sample Image

See how the firestore and storage have to be connected with the same user UID so that the Firestore extension could delete a user easily by deleting the authentication.

If you still want to use the old method:
I noticed that you cannot delete a firestore document that contains one or multiple sub-collections with just delete method. For example, if you want to delete a document that contains 3 sub-collections, in order to delete that document(a user in my case), you have to get all the documents in one of the sub-collection, delete them all, then proceed to do the same to all the other sub-collections in that document. Once all the sub-collections in the document has been deleted, then the document that contains them will be gone itself. That's how Firestore works it seems.

To put it in code:
to delete a document that contains a sub-collection "journal"
Without using the extension, I have to do it like this:

FirebaseFirestore.getInstance().collection("main").document(userid).collection("journal").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (final QueryDocumentSnapshot document : task.getResult()) {
if (document.exists()){
db.collection("main").document(userid).collection("journal").document(document.getId()).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {

}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(SettingsActivity.this, "Journal: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(SettingsActivity.this, "No data in JOURNAL", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(SettingsActivity.this, "Journal task: " + task.getException(), Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(SettingsActivity.this, "Error getting all the documents: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});

If you have multiple sub-collections in that particular document, to delete it you have to repeat that code multiple times for different sub-collections which will make the codes very long.

I hope this is helpful for someone out there who is trying to delete a user from Firestore. :) Use the extension already.

How to delete all documents in Cloud Firestore except one?

As far as I understand your question, I would like to give you an idea.

I think it is not possible to delete with exceptions. But we can make use of batch operations.

As mentioned in this issue, make it for Flutter like this,

WriteBatch _batch = FirebaseFirestore.instance.batch();

QuerySnapshot _query = await FirebaseFirestore.instance.collection('Dashboard').getDocuments();

_query.documents.forEach((doc) {
if(doc.documentID != 'YOUR DATE'){
_batch.delete(doc.ref);
}
});

await _batch.commit();

As mentioned in the issue, it also has some limits!

Reference: https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes



Related Topics



Leave a reply



Submit