Cloud Firestore (Basics)

Cloud Firestore is a flexible, scalable NoSQL document database for mobile, web, and server development from Firebase and Google Cloud Platform.

1. Data Model

Firestore stores data in Documents, which are stored in Collections. Documents can contain nested objects and sub-collections.

2. Basic CRUD Operations

Create (Add Document)

Use addDoc to let Firestore generate an ID, or setDoc to specify your own ID.

import { db } from "../lib/firebase";
import { collection, addDoc, setDoc, doc } from "firebase/firestore";

// Add with auto-generated ID
await addDoc(collection(db, "cities"), {
  name: "Tokyo",
  country: "Japan"
});

// Set with specific ID
await setDoc(doc(db, "cities", "LA"), {
  name: "Los Angeles",
  state: "CA"
});

Read (Get Document)

import { getDoc, doc } from "firebase/firestore";

const docRef = doc(db, "cities", "LA");
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Document data:", docSnap.data());
} else {
  console.log("No such document!");
}

Update

import { updateDoc, doc } from "firebase/firestore";

const washRef = doc(db, "cities", "LA");
await updateDoc(washRef, {
  capital: true
});

Delete

import { deleteDoc, doc } from "firebase/firestore";

await deleteDoc(doc(db, "cities", "LA"));
Key Concept: Firestore is near-real-time by default. If you make a change, it syncs instantly to all connected clients!