Home > Software design >  Unable to batch.delete documents of a subcollection
Unable to batch.delete documents of a subcollection

Time:06-11

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: 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);
}
  • Related