What is Subcollection in Firestore: Explained Simply
subcollection in Firestore is a collection of documents nested inside a document, allowing you to organize data hierarchically. It helps group related data under a specific document, like folders inside folders.How It Works
Think of Firestore like a big filing cabinet. Each drawer is a collection, and inside each drawer are folders called documents. A subcollection is like a smaller drawer inside one of those folders. It lets you organize data inside a document in a neat, nested way.
This means you can have a document about a user, and inside that user document, you can have a subcollection of that user's orders. Each order is its own document inside the subcollection. This structure keeps related data close together and easy to find.
Example
This example shows how to add a subcollection called orders inside a users document in Firestore using JavaScript.
import { getFirestore, doc, collection, addDoc } from 'firebase/firestore'; const db = getFirestore(); async function addOrderToUser(userId) { // Reference to the user document const userDocRef = doc(db, 'users', userId); // Reference to the 'orders' subcollection inside the user document const ordersCollectionRef = collection(userDocRef, 'orders'); // Add a new order document to the subcollection const newOrder = await addDoc(ordersCollectionRef, { item: 'Coffee Mug', quantity: 2, price: 15 }); console.log('Order added with ID:', newOrder.id); } // Example call addOrderToUser('user123');
When to Use
Use subcollections when you want to organize related data that belongs to a specific document. For example:
- Storing a user's orders inside their user document.
- Keeping comments inside a specific blog post document.
- Grouping messages inside a chat room document.
This helps keep your database clean and makes it easier to query related data without mixing unrelated information.
Key Points
- A subcollection is a collection inside a document, creating a nested data structure.
- It helps organize data hierarchically, like folders inside folders.
- Subcollections can have their own documents and further subcollections.
- They make querying related data easier and more efficient.