Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 31 ยท Firebase Cloud Firestore

Reading and Writing Documents

Create, read, update and delete Firestore documents. Learn merge, serverTimestamp, increment, arrayUnion, batched writes and transactions with a runnable stand-in.

Once you know how Firestore organises data, the next step is moving data in and out. The web SDK gives you a handful of functions: addDoc and setDoc to create, getDoc to read, updateDoc to change fields, and deleteDoc to remove. On top of those sit a few special values (increment, array operators, server timestamps) and two ways to group writes: batches and transactions.

The most useful idea in this lesson is that the database can apply a change for you, atomically, instead of you reading a value, changing it in your app and writing it back. That avoids a whole class of bugs where two users edit the same thing at once.

Real Firestore code cannot run here (it needs a Firebase project and a network). SDK snippets are read-only. The runnable examples are stand-ins that mimic how these operations behave, so you can see the idea. They are not the real engine, and real Firestore adds details such as security rules, offline queues and network retries.

The core functions

Write, read, change, remove

addDoc New document, auto ID.
setDoc Create or replace at a known ID.
updateDoc Change some fields. Must exist.
deleteDoc Remove one document.

Reading uses getDoc for one document, getDocs for many.

1 / 2

Here they are in the modular web SDK:

JavaScript
import {
  getFirestore, collection, doc,
  addDoc, setDoc, getDoc, updateDoc, deleteDoc,
} from "firebase/firestore";

const db = getFirestore();

// Create with an auto-generated ID
const ref = await addDoc(collection(db, "tasks"), { title: "Write lesson", done: false });
console.log(ref.id);

// Create or fully replace at an ID you choose
await setDoc(doc(db, "users", "ada"), { name: "Ada", plan: "free" });

// Change only some fields (fails if the document does not exist)
await updateDoc(doc(db, "users", "ada"), { plan: "pro" });

// Read one document
const snap = await getDoc(doc(db, "users", "ada"));
if (snap.exists()) {
  console.log(snap.id, snap.data());
} else {
  console.log("No such document");
}

// Remove it
await deleteDoc(doc(db, "users", "ada"));

A few rules worth memorising:

  • setDoc replaces the whole document by default. Fields you leave out are gone.
  • setDoc(ref, data, { merge: true }) writes only the fields you give and keeps the rest, creating the document if needed.
  • updateDoc fails if the document does not exist, which makes it the safe choice for "change this record I already have".
  • getDoc does not throw for a missing document. You get a snapshot, and snap.exists() tells you.
  • To change a field inside a map, use dot notation as the key: updateDoc(ref, { "address.city": "Porto" }). Without the dot, you would replace the entire address map.

Special values the server applies

Some values are not data but instructions. You send them in place of a normal value, and Firestore applies them on the server so concurrent writers do not overwrite each other:

JavaScript
import { serverTimestamp, increment, arrayUnion, arrayRemove, deleteField } from "firebase/firestore";

await updateDoc(doc(db, "posts", "p1"), {
  views: increment(1),                    // add 1 to the current number
  tags: arrayUnion("firebase"),           // add if not already present
  oldTags: arrayRemove("draft"),          // remove every match
  updatedAt: serverTimestamp(),           // the server's clock, not the user's
  legacyField: deleteField(),             // remove this field
});

serverTimestamp() matters because users' devices have wrong clocks. If two people post "now", you want one trustworthy time source to order them. increment matters because the naive pattern (read views, add one, write it back) loses updates when two people do it at the same moment.

Try it: operators in a stand-in

This stand-in models setDoc, merge, updateDoc and the four operators. The clock is fake and advances by one second per call, so the output is predictable.

JS Atomic update operators in a stand-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 2 shows why setDoc without merge is dangerous on a document other code also writes to. Step 6 shows why updateDoc is the safer call when the document must already exist.

Batched writes

A write batch groups up to 500 writes (set, update, delete) into one operation that either applies completely or not at all. Use it when several documents must change together, such as creating an order and decrementing stock:

JavaScript
import { writeBatch } from "firebase/firestore";

const batch = writeBatch(db);
batch.set(doc(db, "orders", "o-1"), { item: "mug", qty: 2 });
batch.update(doc(db, "products", "mug"), { stock: increment(-2) });
batch.delete(doc(db, "carts", "ada"));
await batch.commit();   // all three, or none

A batch cannot read. It only sends a fixed list of writes. If your decision depends on current data, use a transaction.

Transactions

A transaction reads documents, then writes based on what it read. If any document it read was changed by someone else before the commit, Firestore runs your function again with fresh data, up to a retry limit.

JavaScript
import { runTransaction } from "firebase/firestore";

await runTransaction(db, async tx => {
  const ref = doc(db, "products", "mug");
  const snap = await tx.get(ref);
  const stock = snap.data().stock;
  if (stock < 2) throw new Error("Not enough stock");
  tx.update(ref, { stock: stock - 2 });
});

Two consequences: all reads in a transaction come before its writes, and your function must not have side effects (like sending an email) because it may run more than once.

Try it: batch atomicity and transaction retry

This stand-in keeps a version number per document. A batch validates everything before applying anything. A transaction remembers the versions it read and retries if they changed. We simulate a competing writer on the first attempt.

JS Batch all-or-nothing and transaction retry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first attempt computed 10 - 2 = 8, which would have erased the other sale. Because the version changed, the retry read 7 and wrote 5. That re-run is exactly what protects you in real Firestore.

Which one should you use?

  • A single independent change: setDoc / updateDoc, with increment or arrayUnion if concurrent writers are possible.
  • Several writes that need no reads: a batch.
  • Writes that depend on values you read: a transaction.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A document has fields title and views. You call setDoc(ref, { views: 5 }) with no options. What is left?

    Without merge: true, setDoc replaces the whole document, so title is removed.
  2. 2. Why use increment(1) instead of reading views, adding one and writing it back?

    The read-modify-write pattern can overwrite another user's change. The server applies the increment to the current value.
  3. 3. What can a write batch NOT do?

    A batch is a fixed list of writes. If your writes depend on what you read, use a transaction.
  4. 4. Why must a transaction function avoid side effects such as sending an email?

    On a conflict the function is retried, so a side effect could happen more than once.

Summary

  • addDoc makes a document with an auto ID; setDoc creates or replaces at an ID; updateDoc changes fields and fails if the document is missing.
  • setDoc with { merge: true } keeps unlisted fields; dot notation edits fields inside maps.
  • increment, arrayUnion, arrayRemove, serverTimestamp and deleteField are applied by the server.
  • A batch applies up to 500 writes all-or-nothing but cannot read.
  • A transaction reads then writes and retries on conflict, so keep it free of side effects.

Next: Queries, Indexes and Pagination.