I have implemented the following a function to delete data using a batch. But it's giving me an unhandled exception saying that "Cannot modify a WriteBatch that has been committed. I think it's because of the for loop I'm using.
data.forEach(async (element: any) => {
const snapshot = await db
.collection("car")
.doc(element.brand)
.collection("model")
.doc(element.model)
.collection("year")
.orderBy("year")
.get();
snapshot.forEach(async (doc) => {
if (element.service === "Car Spa") {
console.log("Cond1")
const ref1 = db
.collection(element.service)
.doc(element.sub_service)
.collection("Body Type")
.doc(element.bodyType)
.collection("model")
.doc(element.model)
.collection("mechanic")
.doc("email@gmail.com")
batch.delete(ref1);
operationCounter++;
} else {
console.log("Cond:2")
const ref2 = db
.collection(element.service)
.doc(element.sub_service)
.collection("vehicle")
.doc(element.brand)
.collection("model")
.doc(element.model)
.collection("year")
.doc(doc.data().year.toString())
.collection("mechanic")
.doc("email@gmail.com")
batch.delete(ref2)
operationCounter++;
}
let _id =
element.service +
element.sub_service +
element.brand +
element.model +
doc.id;
const ref3 = db
.collection("mechanics")
.doc("email@gmail.com")
.collection("services")
.doc(_id)
batch.delete(ref3);
operationCounter++;
if (operationCounter === 500) {
console.log("MORE THAN 500");
batches.push(batch.commit());
batch = db.batch();
operationCounter = 0;
}
});
});
if (batches.length === 0) {
await batch.commit().then(() => console.log("DONE ONE BAtch"));
} else {
await Promise.all(batches).then(() => console.log("DONE"));
}
Please suggest a way to do the batch deletion inside the loop efficiently. Thanks in advance!