0
0
GcpConceptBeginner · 3 min read

What is Subcollection in Firestore: Explained Simply

A subcollection in Firestore is a collection of documents nested inside a specific document. It helps organize related data hierarchically, like folders inside folders, allowing you to group data under a parent document.
⚙️

How It Works

Think of Firestore like a big filing cabinet. Each drawer is a collection holding many files called documents. A subcollection is like a smaller drawer inside one of those files. It lets you store more detailed or related information directly linked to that specific document.

This nesting means you can organize data in layers. For example, a user document can have a subcollection of their orders. Each order is a document inside that subcollection. This structure keeps data tidy and easy to find, just like organizing papers in folders and subfolders.

💻

Example

This example shows how to create a subcollection called orders inside a user 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 this user document
  const ordersSubcollectionRef = collection(userDocRef, 'orders');

  // Add a new order document to the subcollection
  const newOrder = await addDoc(ordersSubcollectionRef, {
    item: 'Laptop',
    price: 1200,
    status: 'shipped'
  });

  return newOrder.id;
}

// Usage example
addOrderToUser('user123').then(orderId => {
  console.log('New order added with ID:', orderId);
});
Output
New order added with ID: <generated_document_id>
🎯

When to Use

Use subcollections when you want to group related data under a specific document to keep your database organized. For example:

  • Storing user orders inside each user document.
  • Keeping comments inside a specific blog post document.
  • Organizing messages inside a chat room document.

This helps avoid very large flat collections and makes it easier to query related data efficiently.

Key Points

  • Subcollections are collections inside documents, creating a nested data structure.
  • They help organize related data clearly and logically.
  • Each subcollection can have its own documents and further subcollections.
  • Subcollections are queried separately from their parent documents.

Key Takeaways

A subcollection is a nested collection inside a Firestore document for organizing related data.
Use subcollections to group data like orders under users or comments under posts.
Subcollections keep your database structured and easier to manage.
You access subcollections by referencing their parent document first.
Each subcollection can have its own documents and even more nested subcollections.