How to Add or Remove Fields in Firestore Collection Documents

Emiliano
EmilianoJune 3, 2024

Get the Firestore Reference

To get started, you need to import the required modules and have access to your Firestore database:

javascript
import { getFirestore, collection, getDocs, writeBatch, doc, deleteField } from "firebase/firestore";

const firestore = getFirestore();

Create a Batch

A batch allows you to group multiple write operations, such as updates or deletions, into a single request. This ensures that all operations are performed atomically, meaning all modifications within the batch are applied simultaneously and completely.

If any operation fails, all operations in the batch are rolled back, guaranteeing that the database is not left in an inconsistent state.

javascript
const batch = writeBatch(firestore);

Retrieve All Documents from the Collection

To modify all documents within a collection, you first need to retrieve them:

javascript
const postsSnapshot = await getDocs(collection(firestore, "posts"));

Iterate Over Documents to Update and/or Remove Fields

With the documents in hand, you can iterate over each one to update or delete the necessary fields. Here is how to add a field called newField and how to delete a field called oldField:

javascript
postsSnapshot.forEach((docSnapshot) => {
  const docRef = docSnapshot.ref;

  batch.update(docRef, {
    newField: [],
    oldField: deleteField(),
  });
});

Apply the Updates and Deletions

Finally, after preparing all the modifications, it is time to apply them using batch.commit():

javascript
await batch.commit();

This method ensures that all updates and deletions are executed efficiently and without errors.