Firebase Tutorial
- Home
- Introduction
- Project Setup
- Authentication (Email/Pass)
- Social Authentication
- Cloud Firestore (Basics)
- Firestore Queries
- Real-time Updates
- Firestore Security Rules
- Cloud Storage
- Storage Security Rules
- Cloud Functions (Intro)
- Triggering Functions
- Firebase Hosting
- Firebase Analytics
- Crashlytics & Performance
- Remote Config
- App Check
- Offline Persistence
- Firebase with Next.js
- Best Practices
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!