What is the difference between `set()`, `add()`, and `update()` in Firestore?
Answer
These three methods write data but with different behaviors: (1) setDoc(ref, data) — creates OR completely replaces a document at the specified path. If the doc exists, all existing fields are overwritten. If it doesn't exist, it's created. setDoc(doc(db, "users", "alice"), { name: "Alice" }) — you specify the document ID. setDoc(ref, data, { merge: true }) merges instead of overwrites; (2) addDoc(collection, data) — creates a new document with an auto-generated unique ID. Used when you don't care about the document ID. Returns a DocumentReference with the new ID: const ref = await addDoc(collection(db, "posts"), { title: "Hello" }); (3) updateDoc(ref, data) — updates only the specified fields of an existing document. Fails if the document doesn't exist. Does not affect unspecified fields. Summary: setDoc for known IDs (upsert); addDoc for auto-IDs; updateDoc for partial updates on existing docs.