Firebase
Firestore
Store and sync data with Cloud Firestore.
Overview
Cloud Firestore is a NoSQL document database that lets you store, sync, and query data for your mobile and web apps.
Data Model
Firestore stores data in documents organized into collections:
users (collection)
└── userId (document)
├── name: "John Doe"
├── email: "john@example.com"
└── posts (subcollection)
└── postId (document)
├── title: "Hello"
└── content: "World"
Reading Data
import FirebaseFirestore
let db = Firestore.firestore()
let document = try await db.collection("users").document(userId).getDocument()
let user = try document.data(as: User.self)
Writing Data
let user = User(name: "John Doe", email: "john@example.com")
try await db.collection("users").document(userId).setData(from: user)
Real-time Updates
Listen to changes in real-time:
db.collection("posts")
.addSnapshotListener { snapshot, error in
guard let documents = snapshot?.documents else { return }
let posts = documents.compactMap { try? $0.data(as: Post.self) }
}
Security Rules
Protect your data with security rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}