How to Use Subcollections in Firebase Firestore and Create Multiple Child Items

When working with Firebase Firestore, you’ll often need to store related data in a structured way. For example, an Order document might contain multiple Items, or a Post might have many Comments. Firestore provides a powerful way to handle this scenario using subcollections.

In this article, we’ll cover:

  1. 🔹 What subcollections are in Firestore
  2. 🔹 When and why to use them
  3. 🔹 How to create a subcollection inside a document
  4. 🔹 How to add multiple child documents efficiently
  5. 🔹 Best practices to keep your data structured

1. What Are Subcollections?

Firestore is a NoSQL document database. The structure looks like this:

  • Collection → contains documents
  • Document → can contain fields and subcollections
  • Subcollection → another collection stored under a specific document

👉 Example structure:

/posts/{postId}/comments/{commentId}

Here:

  • posts is a collection.
  • Each postId is a document.
  • Inside each post document, there’s a subcollection comments containing many child documents.

2. When to Use Subcollections

Use subcollections when:

  • You have 1-to-many relationships (e.g., a user has many orders, a post has many comments).
  • Data might grow large and you don’t want the parent document to become too heavy.
  • You need independent queries on the child data (e.g., fetch all comments for a post).

⚠️ Note: Deleting a parent document does not automatically delete its subcollections—you need to handle cleanup separately.

3. Creating a Subcollection

Example: Adding Comments to a Post (JavaScript, Firebase v9+)

import { getFirestore, doc, collection, addDoc } from "firebase/firestore";

const db = getFirestore();

// Reference to a specific post
const postRef = doc(db, "posts", "post123");

// Reference to the "comments" subcollection inside this post
const commentsRef = collection(postRef, "comments");

// Add a comment
await addDoc(commentsRef, {
  author: "Alice",
  text: "This is my first comment!",
  createdAt: Date.now()
});

Here:

  • "posts" is the parent collection.
  • "post123" is a document ID.
  • "comments" is the subcollection inside post123.

4. Adding Multiple Child Documents

You often need to insert multiple child items into a subcollection (e.g., multiple order items at once). There are two main ways:

A. Add in a Loop

const items = [
  { name: "Burger", price: 150 },
  { name: "Fries", price: 80 },
  { name: "Coke", price: 40 },
];

const orderRef = doc(db, "orders", "order567");
const itemsRef = collection(orderRef, "items");

for (const item of items) {
  await addDoc(itemsRef, item);
}

B. Use a Batch Write (Efficient for Many Documents)

import { writeBatch, collection, doc } from "firebase/firestore";

const batch = writeBatch(db);
const orderRef = doc(db, "orders", "order567");
const itemsRef = collection(orderRef, "items");

const items = [
  { name: "Burger", price: 150 },
  { name: "Fries", price: 80 },
  { name: "Coke", price: 40 },
];

items.forEach(item => {
  const itemDoc = doc(itemsRef); // auto ID
  batch.set(itemDoc, item);
});

// Commit all at once
await batch.commit();

batch.commit() writes everything in a single request (faster and atomic).

5. Best Practices

  • Use subcollections for scalability – don’t put huge arrays inside documents.
  • Name collections consistently – e.g., always use "comments" for post comments, not "postComments123".
  • Consider collection-group queries – Firestore allows you to query across all subcollections of the same name.
  • Example: db.collectionGroup("comments").where("author", "==", "Alice").
  • Handle cascading deletes – If you delete a post, write a Cloud Function to also delete its comments.

✅ Summary

  • Firestore allows collections inside documents, called subcollections.
  • Subcollections are ideal for one-to-many relationships like orders → items or posts → comments.
  • You can add child items with addDoc() or more efficiently with batch writes.
  • Always plan your structure for scalability and query performance.

🔥 With this knowledge, you can now structure your Firestore data cleanly, keeping parent documents lightweight while storing large sets of related child data in subcollections.

Would you like me to also show the same examples in Next.js (TypeScript) since your project uses Next.js + Firebase, so it matches directly with your codebase?

Leave a comment

Your email address will not be published. Required fields are marked *