How to Delete Multiple Documents From Firestore?

By Hemanta Sundaray on 2023-01-05

Imagine you have an e-commerce application and you have a list of cart items for a specific user.

Ecommerce cart

When the user successfully checks out and pays for the products in the cart, you want to clear the cart items from the Firestore database.

Ecommerce empty cart

The "clear cart items" scenario is just one example. Your use case might be different. Regardless of your specific use case, the goal is the same: you want to delete multiple documents from the Firestore database. Here is how you can do it.

Below, we have a function named clearCartItems that deletes multiple documents from the Cloud Firestore.

export const clearCartItems = async userId => {
  const batch = writeBatch(db)

  const cartItemsQuery = query(
    collection(db, "cartItems"),
    where("userId", "==", userId)
  )
  const cartItemsQuerySnapshot = await getDocs(cartItemsQuery)
  cartItemsQuerySnapshot.forEach(doc => batch.delete(doc.ref))

  batch.commit()
}

Let's go over what each line of code does:

const batch = writeBatch(db)

First, we create a batch object using the writeBatch function. This will allow us to perform multiple write operations in a single write operation.

const cartItemsQuery = query(
  collection(db, "cartItems"),
  where("userId", "==", userId)
)

Next, we create a query that selects all the documents in the cartItems collection where the userId field matches the provided userId. This will allow us to select only the documents that we want to delete.

const cartItemsQuerySnapshot = await getDocs(cartItemsQuery)

We execute the query and get a snapshot of the matching documents using the getDocs function.

cartItemsQuerySnapshot.forEach(doc => batch.delete(doc.ref))

Finally, we loop through the snapshot and add a delete operation for each document to the batch using the batch.delete(documentRef) function.

batch.commit()

Once we've added all the delete operations to the batch, we can execute the batch write using the batch.commit() function. This will delete all the selected documents in a single write operation, which can be more efficient than deleting the documents one by one.

That's it! With just a few lines of code, we've created a function that can delete multiple documents from the Cloud Firestore.

Join the Newsletter