Batch Writes and Transactions
Batch writes allow you to execute multiple write operations as a single atomic unit. This means that either all of the operations succeed, or none of them do.
Example: Batch Write
import { writeBatch, doc } from "firebase/firestore";
// Initialize a batch
const batch = writeBatch(db);
// Create references to the documents
const userRef1 = doc(db, "users", "userId1");
const userRef2 = doc(db, "users", "userId2");
// Set data for each document
batch.set(userRef1, { name: "Alice", email: "alice@example.com" });
batch.set(userRef2, { name: "Bob", email: "bob@example.com" });
// Commit the batch
await batch.commit();
Explanation:This code snippet demonstrates how to use batch writes in Firestore to execute multiple write operations as a single atomic unit. It initializes a batch, creates references to two user documents (“userId1” and “userId2”), sets data for each document, and commits the batch to apply the changes atomically.
1. Transactions
Transactions are used when you need to read a document and then write to it based on the read data. Firestore ensures that the transaction is executed atomically.
Example: Transaction
import { runTransaction, doc } from "firebase/firestore";
// Create a reference to the user document
const userRef = doc(db, "users", "userId123");
// Run the transaction
await runTransaction(db, async (transaction) => {
const userSnap = await transaction.get(userRef);
if (!userSnap.exists()) {
throw "User does not exist!";
}
const newEmail = "new.email@example.com";
transaction.update(userRef, { email: newEmail });
});
Explanation:This code snippet demonstrates how to use transactions in Firestore. It creates a reference to a user document (“userId123”), then runs a transaction to update the user’s email. The transaction first checks if the user document exists, and if so, updates the email field to “new.email@example.com”.
2. Real-Time Updates
Firestore can listen to changes in your data in real-time, allowing your app to stay up-to-date without polling the server.
Example: Real-Time Listener
import { doc, onSnapshot } from "firebase/firestore";
// Create a reference to the user document
const userRef = doc(db, "users", "userId123");
// Listen for real-time updates
onSnapshot(userRef, (doc) => {
if (doc.exists()) {
console.log("Current data: ", doc.data());
} else {
console.log("No such document!");
}
});
Explanation:This code sets up a real-time listener for changes to a specific user document (“userId123”). When the document is modified, the listener logs the current data of the document. If the document doesn’t exist, it logs “No such document!”.
Writing and Reading Data in Cloud Firestore
Cloud Firestore is a NoSQL document database built for automatic scaling, high performance, and ease of application development. In this article, we will explore how to write and read data in Cloud Firestore along with complete with detailed examples and. Whether you are a beginner or looking to refine your understanding, this guide will walk you through the basics in a straightforward, easy-to-understand manner.