What is Document in Firestore: Simple Explanation and Example
document in Firestore is a single record that stores data as key-value pairs inside a collection. It is like a row in a database table but more flexible, allowing nested data and different fields per document.How It Works
Think of Firestore as a big filing cabinet. Each collection is like a drawer in that cabinet, and inside each drawer are many documents. Each document holds information about one item, just like a file folder holds papers about one subject.
Each document stores data as pairs of names and values, like labels and their details. For example, a document about a book might have a title, author, and number of pages. Documents can also hold nested data, like an address inside a user profile.
This setup lets you organize data in a flexible way without strict rules, so each document can have different fields if needed. Firestore automatically assigns a unique ID to each document or you can choose your own.
Example
This example shows how to create and read a document in Firestore using JavaScript.
import { initializeApp } from 'firebase/app'; import { getFirestore, doc, setDoc, getDoc } from 'firebase/firestore'; const firebaseConfig = { apiKey: 'your-api-key', authDomain: 'your-auth-domain', projectId: 'your-project-id' }; const app = initializeApp(firebaseConfig); const db = getFirestore(app); async function addAndReadDocument() { const docRef = doc(db, 'books', 'book1'); await setDoc(docRef, { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', pages: 180 }); const docSnap = await getDoc(docRef); if (docSnap.exists()) { console.log('Document data:', docSnap.data()); } else { console.log('No such document!'); } } addAndReadDocument();
When to Use
Use Firestore documents when you need to store and organize data in a flexible, scalable way. Documents are great for user profiles, product details, messages, or any data that fits naturally into key-value pairs.
For example, an app that tracks books can store each book as a document with fields like title, author, and pages. If you want to add reviews later, you can add nested data or create related collections.
Firestore documents are also useful when you want real-time updates, offline support, and easy integration with mobile or web apps.
Key Points
- A document is a single record in Firestore storing data as key-value pairs.
- Documents live inside collections, like files in drawers.
- Each document has a unique ID and can store nested data.
- Documents are flexible and do not require all fields to be the same.
- Use documents to organize app data that needs real-time syncing and offline support.