/firebase-tutorials

How to batch write in Firestore?

Master Firestore batch writes with this guide: set up Firebase, add the SDK, create & commit batch operations, and handle errors for atomic updates.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to batch write in Firestore?

 

Step 1: Set Up Your Firebase Project

 

Before you can use Firestore for batch writing, ensure you have a Firebase project set up. If you're new to Firebase, go to the Firebase Console and create a new project. Follow the instructions to register your app and get your Firebase configuration.

 

Step 2: Add Firebase SDK to Your Project

 

To interact with Firestore, you need to add Firebase SDK to your project. Below is an instruction for JavaScript. For other platforms, please refer to Firebase documentation.

  1. Install Firebase:
npm install firebase
  1. Import Firebase in your script:
<script type="module">
  // Import the functions you need from the SDKs you need
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.x.x/firebase-app.js";
  import { getFirestore } from "https://www.gstatic.com/firebasejs/9.x.x/firebase-firestore.js";
  
  // TODO: Replace with your project's customized code snippet
  const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_PROJECT_ID.appspot.com",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID",
  };

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);

  // Initialize Firestore
  const db = getFirestore(app);
</script>

 

Step 3: Initialize Firestore Batch

 

Firestore provides a batch object that lets you perform multiple write operations as a single atomic unit.

import { writeBatch, doc } from "https://www.gstatic.com/firebasejs/9.x.x/firebase-firestore.js";

const batch = writeBatch(db);

 

Step 4: Create Write Operations

 

Add writes to the batch. You can set, update, or delete documents as needed.

// Set a document
const docRef1 = doc(db, "collectionName", "docId1");
batch.set(docRef1, { 
  field1: "value1",
  field2: "value2"
});

// Update another document
const docRef2 = doc(db, "collectionName", "docId2");
batch.update(docRef2, { 
  field3: "newValue3"
});

// Delete a document
const docRef3 = doc(db, "collectionName", "docId3");
batch.delete(docRef3);

 

Step 5: Commit the Batch

 

After adding all desired operations to the batch, you need to commit the batch. This will send all the operations to Firestore in a single request.

batch.commit().then(() => {
  console.log("Batch write successfully committed!");
}).catch((error) => {
  console.error("Error committing batch write: ", error);
});

 

Step 6: Handle Errors

 

Error handling is crucial to ensure that your application can gracefully manage any issues that arise during the batch commit process.

batch.commit()
  .then(() => {
    console.log("Batch write successfully committed!");
  })
  .catch((error) => {
    console.error("Error committing batch write: ", error);
    // Handle errors here, maybe retry the operation or alert the user
  });

 

This detailed and comprehensive guide outlines how to perform batch writing in Firestore using Firebase. Follow the steps carefully, and refer to the official Firebase documentation for more advanced use cases and comprehensive platform support.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022