# Reading and Writing Documents — Firebase

Source: https://www.skillbyai.com/en/firebase/fs-rw

> getDoc, setDoc, updateDoc, addDoc.

## The core write functions

`getDoc` reads one document and returns a snapshot (`exists()`, `data()`, `id`). `setDoc` creates or **overwrites** a document; with `{ merge: true }` it merges fields instead. `updateDoc` changes specific fields and **fails if the document does not exist**; dotted paths such as `"address.city"` update nested fields. `addDoc` adds a document with an auto-generated id. `deleteDoc` removes one. Use **`serverTimestamp()`** instead of the client clock for times, and field transforms such as `increment()`, `arrayUnion()` and `arrayRemove()` for safe concurrent updates.

## CRUD with the modular SDK

TypeScript.

```typescript
import {
  doc, collection, getDoc, setDoc, updateDoc, addDoc, deleteDoc,
  serverTimestamp, increment, arrayUnion,
} from "firebase/firestore";

const profileRef = doc(db, "profiles", uid);

await setDoc(profileRef, { displayName: "Asha", createdAt: serverTimestamp() });
await setDoc(profileRef, { bio: "Builder" }, { merge: true }); // keep other fields
await updateDoc(profileRef, { "address.city": "Pune", loginCount: increment(1) });

const snap = await getDoc(profileRef);
console.log(snap.exists() ? snap.data() : "missing");

const postRef = await addDoc(collection(db, "posts"), {
  authorId: uid, title: "Hello", tags: [], createdAt: serverTimestamp(),
});
await updateDoc(postRef, { tags: arrayUnion("intro") });
await deleteDoc(postRef);
```

## Type your converters

In TypeScript, `withConverter` on a reference maps snapshots to typed objects, so `data()` returns your model type instead of `DocumentData`.

**Quiz:** What does setDoc do without the merge option when the document already exists?

- [ ] Appends a new version
- [ ] Fails with not-found
- [x] Overwrites the whole document with the new data
- [ ] Merges only changed fields

*Answer:* Overwrites the whole document with the new data. Use { merge: true } or updateDoc to change some fields.
