What is considered most efficient when deleting a Firestore collection?
Performing deletions using batches:
async function deleteCollection(db, collectionPath, batchSize) {
const collectionRef = db.collection(collectionPath);
const query = collectionRef.orderBy('__name__').limit(batchSize);
return new Promise((resolve, reject) => {
deleteQueryBatch(db, query, resolve).catch(reject);
});
}
async function deleteQueryBatch(db, query, resolve) {
const snapshot = await query.get();
const batchSize = snapshot.size;
if (batchSize === 0) {
// When there are no documents left, we are done
resolve();
return;
}
// Delete documents in a batch
const batch = db.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
await batch.commit();
// Recurse on the next process tick, to avoid
// exploding the stack.
process.nextTick(() => {
deleteQueryBatch(db, query, resolve);
});
}
Or using the firestore's default recursiveDelete()
method:
await firestore.recursiveDelete(collectionRef);
Note: The collection I am trying to delete doesn't have nested sub-collections. Also, I am running this code in a cloud function.
/messages (C)
-message_id_1 (D)
-message_id_2 (D)
-message_id_3 (D)
...
-message_id_10000 (D)
CodePudding user response:
The recursiveDelete
function uses the same mechanism as batched writes under the hood, so any performance difference should be negligible.