Lesson 7 / 25

Documents, Collections and Subcollections

The hierarchical data model.

Paths alternate collection and document

Firestore data lives in documents: maps of fields (strings, numbers, booleans, timestamps, geopoints, references, arrays and nested maps). Documents live in collections, and a document can own subcollections, so paths alternate: users/alice/orders/o1. Collections are created implicitly when you write the first document, and deleting a document does not delete its subcollections. Documents have a size limit (1 MiB at the time of writing, check the docs), and a query on a collection returns documents from that collection only; collection group queries search every collection with the same ID, such as all orders subcollections.

Documents in collections

Firestore stores JSON-like documents in collections, and you design the shape around the queries your screens need.

Three ideas: documents and collections, modelling for queries, reads and writes.
Figure 3.1 — Collections, subcollections and modelling for reads.

References to documents and collections

TypeScript.

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

const db = getFirestore(app);

const userRef = doc(db, "users", "alice");                 // users/alice
const ordersCol = collection(db, "users", "alice", "orders"); // users/alice/orders
const orderRef = doc(ordersCol, "o1");                       // users/alice/orders/o1
const newOrderRef = doc(ordersCol);                          // auto-generated id

// every collection named "orders", at any depth
const allOrders = collectionGroup(db, "orders");

Folders and files

Collections are folders, documents are files with fields, and a file can have its own folders inside it; deleting a file does not empty those folders automatically.

Quick check: What happens to a document's subcollections when the document is deleted from the client?

  • They remain and must be deleted separately
  • They are deleted automatically
  • They move to the parent collection
  • The delete is rejected
Answer

They remain and must be deleted separately — Subcollections are independent of the parent document's existence.