Benefits:
- Better Data Organization – You can create logical hierarchies that mirror real-world relationships (e.g., users → posts → comments)
- Improved Query Performance – Queries on subcollections are scoped to that specific parent document, making them faster and more efficient
- Granular Security Rules – You can set different access permissions for subcollections, allowing fine-grained security control
- Scalability – Documents have a 1MB size limit, but subcollections let you store unlimited related data without hitting this limit
- Easier Data Management – Related data stays together conceptually while being separate technically, making it easier to query and maintain
- Cost Efficiency – You only read/write what you need rather than fetching large nested objects.
How to Create Subcollections:
JavaScript/Web SDK:
import { collection, doc, setDoc, addDoc } from ‘firebase/firestore’;
import { db } from ‘./firebase-config’;
// Create a subcollection under a specific document
const userRef = doc(db, ‘users’, ‘userId123’);
const postsRef = collection(userRef, ‘posts’);
// Add a document to the subcollection
await addDoc(postsRef, {
title: ‘My First Post’,
content: ‘Hello World’,
timestamp: new Date()
});
// Or with a specific ID
await setDoc(doc(postsRef, ‘post1’), {
title: ‘Specific Post’,
content: ‘Content here’
});
Reading from Subcollections:
const handleInputChange = (
id: string,
field: string,
value: string | boolean | number
) => {
// … existing code …
if (field === “ship_method”) {
// value is always a string (“” when cleared)
const newValue = String(value);
setPosData(prev =>
prev.map(r => (r.id === id ? { …r, ship_method: newValue } : r))
);
} else if (field === “qty”) {
// … qty logic …
} else {
setPosData(prev =>
prev.map(r => (r.id === id ? { …r, [field]: value } : r))
);
}
setEditedRows(prev => ({ …prev, [id]: true }));
seteditablefields(prev => ({
…prev,
[id]: { …(prev[id] || {}), [field]: true },
}));
};
Important Notes:
- Deleting a parent document doesn’t automatically delete its subcollections
- You can query across all subcollections with the same name using Collection Group Queries
- Subcollections can have their own subcollections (nested hierarchy)