0
0
FirebaseConceptBeginner · 3 min read

What is Subcollection in Firestore: Explained Simply

A 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.

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');
Output
Order added with ID: <generated_document_id>
🎯

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.

Key Takeaways

A subcollection is a nested collection inside a Firestore document for hierarchical data organization.
Use subcollections to group related data like user orders or post comments under a single document.
Subcollections keep your database structured and make querying related data simpler.
You can nest subcollections multiple levels deep for complex data relationships.