Skip to content
Advertisement

Unable to batch.delete documents of a subcollection

I have a collection called display and each document inside the display has a subcollection called history. There’s no error, though, it does not delete the documents in Firestore. After selecting the row to be deleted, it is gone when you click delete. However, once you reload the screen, the data deleted was still there, meaning it wasn’t successfully deleted in Firestore.

I recreated the error I have in the code sandbox: https://codesandbox.io/s/batch-delete-not-working-vcqcd3?file=/src/App.js

 async function batchDeleteDocuments(docID, historyId) {
    try {
      console.log(docID, "docs");
      console.log(historyId, "history");

      const batch = writeBatch(db);

      for (let i = 0; i < docID.length; i++) {
        const docRef = doc(db, "display", docID[i], "history", historyId[i]);
        console.log(i, "deleting", docRef.path);
        batch.delete(docRef);
      }

      await batch.commit();
      console.log("deleted");
    } catch (err) {
      console.log(err);
    }
  }

Advertisement

Answer

Upon checking your codesandbox, the field docID has whitespace at the beginning of the string. See screenshot of your codesandbox logs: enter image description here

Digging deeper into your code, I’ve found no issues with how you fetch your data. It’s just that when you try to log your doc.data() in this query:

const getUsers = async () => {
    const listUsers = query(collectionGroup(db, "history"));
    const querySnapshot = await getDocs(listUsers);
    const arr = [];
    querySnapshot.forEach((doc) => {
        console.log(doc.id, " => ", doc.data());
        arr.push({
            ...doc.data(),
            id: doc.id
        });
    });
    if (isMounted) {
        setUsers(arr);
    }
};

The value of docID on your document has whitespace on it. Check the values of docID in your documents of the history collection and make sure that you removed all the whitespace on it. enter image description here

I also tried to replace the docID[i] in this query and successfully deleted the document.

// Try to change docID[i] to hard-coded value.
const docRef = doc(db, "display", "Tv9xj0pC9wTjr59MPsJw", "history", historyId[i]);

You can also use the trim() method for the workaround. See code below:

for (let i = 0; i < docID.length; i++) {
    console.log(docID[i].trim());
    const docRef = doc(
        db,
        "display",
        docID[i].trim(),
        "history",
        historyId[i]
    );
    console.log(i, "deleting", docRef.path);
    batch.delete(docRef);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement