Firestore & Storage
Configure and use Firestore database and Cloud Storage for your project.
Firestore is a NoSQL document database for storing structured data. Cloud Storage handles file uploads like images and documents. Both are commonly used together in Olive Code projects.
Firestore organizes data into collections and documents. Each document contains fields and can have subcollections.
import {
getFirestore,
collection,
doc,
getDoc,
getDocs,
setDoc,
addDoc,
updateDoc,
deleteDoc,
query,
where,
orderBy
} from 'firebase/firestore';
const db = getFirestore();
// Add a document with auto-generated ID
async function addUser(userData) {
const docRef = await addDoc(collection(db, 'users'), userData);
return docRef.id;
}
// Set a document with specific ID
async function setUser(userId, userData) {
await setDoc(doc(db, 'users', userId), userData);
}
// Get a single document
async function getUser(userId) {
const docSnap = await getDoc(doc(db, 'users', userId));
if (docSnap.exists()) {
return { id: docSnap.id, ...docSnap.data() };
}
return null;
}
// Get all documents in a collection
async function getAllUsers() {
const querySnapshot = await getDocs(collection(db, 'users'));
return querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
}
// Query with filters
async function getActiveUsers() {
const q = query(
collection(db, 'users'),
where('status', '==', 'active'),
orderBy('createdAt', 'desc')
);
const querySnapshot = await getDocs(q);
return querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
}
// Update a document
async function updateUser(userId, updates) {
await updateDoc(doc(db, 'users', userId), updates);
}
// Delete a document
async function deleteUser(userId) {
await deleteDoc(doc(db, 'users', userId));
}Firestore security rules control who can read and write data. Configure them in the Firebase Console under Firestore → Rules.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Users can only read/write their own document
match /users/{userId} {
allow read, write: if request.auth != null
&& request.auth.uid == userId;
}
// Public read, authenticated write
match /posts/{postId} {
allow read: if true;
allow write: if request.auth != null;
}
// Only authenticated users
match /private/{document=**} {
allow read, write: if request.auth != null;
}
}
}Never leave your database open to the public. Always configure proper security rules before deploying to production. Test rules using the Firebase Console's Rules Playground.
Cloud Storage is used for storing user-uploaded files like images, videos, and documents.
import {
getStorage,
ref,
uploadBytes,
uploadBytesResumable,
getDownloadURL,
deleteObject
} from 'firebase/storage';
const storage = getStorage();
// Simple upload
async function uploadFile(file, path) {
const storageRef = ref(storage, path);
const snapshot = await uploadBytes(storageRef, file);
const downloadURL = await getDownloadURL(snapshot.ref);
return downloadURL;
}
// Upload with progress tracking
function uploadWithProgress(file, path, onProgress) {
const storageRef = ref(storage, path);
const uploadTask = uploadBytesResumable(storageRef, file);
return new Promise((resolve, reject) => {
uploadTask.on('state_changed',
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
onProgress?.(progress);
},
(error) => reject(error),
async () => {
const downloadURL = await getDownloadURL(uploadTask.snapshot.ref);
resolve(downloadURL);
}
);
});
}
// Get download URL for existing file
async function getFileURL(path) {
const storageRef = ref(storage, path);
return await getDownloadURL(storageRef);
}
// Delete a file
async function deleteFile(path) {
const storageRef = ref(storage, path);
await deleteObject(storageRef);
}Configure storage security rules in Firebase Console under Storage → Rules.
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
// Users can only access their own folder
match /users/{userId}/{allPaths=**} {
allow read, write: if request.auth != null
&& request.auth.uid == userId;
}
// Public read for profile images
match /public/{allPaths=**} {
allow read: if true;
allow write: if request.auth != null;
}
// Limit file size (5MB)
match /{allPaths=**} {
allow write: if request.resource.size < 5 * 1024 * 1024;
}
}
}Organize files by user ID (e.g., /users/[uid]/profile.jpg) to make security rules simpler and queries more efficient.