/firebase-tutorials

How to structure data in Firestore?

Learn how to organize Firestore data with collections, documents, and subcollections for efficient queries, strong security, and optimal indexing.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to structure data in Firestore?

 

Step 1: Understand Firestore's Data Model

 

Firestore, the scalable NoSQL database from Firebase, structures its data hierarchically using collections and documents. A document is a lightweight record that contains fields, and each document can exist within a collection or nested within subcollections. Start by understanding these core concepts:

  • Collections: Containers that hold multiple documents, similar to tables in SQL.
  • Documents: Individual records consisting of fields which may store various data types.
  • Fields: Key-value pairs within a document.
  • Subcollections: Collections that are tied to a parent document.

Knowing these concepts helps lay the groundwork for structuring your data effectively.

 

Step 2: Plan Your Data Structure

 

Before you begin coding, plan how your data should be organized. Consider how your application's data will be queried since Firestore excels with document-based queries over multiple queries to outright join collections:

  • Identify collections: Decide what major categories your data should be grouped into.
  • Design document structure: Determine the fields and possible subcollections each document will have.
  • Consider references: Identify data that will reference other documents.

 

Step 3: Create Collections and Documents

 

To create collections and documents, you'll need to use Firestore's SDK. Here’s an example using Firebase's JavaScript SDK:

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

const db = getFirestore();
const usersCollection = collection(db, 'users');

async function addUser() {
  try {
    const docRef = await addDoc(usersCollection, {
      name: 'John Doe',
      email: '[email protected]'
    });
    console.log('Document written with ID: ', docRef.id);
  } catch (e) {
    console.error('Error adding document: ', e);
  }
}

addUser();

In this snippet:

  • You're importing functions from Firebase to interact with Firestore.
  • You create a reference to a 'users' collection.
  • You add a new document with specified fields to the collection.

 

Step 4: Nest Subcollections Within Documents

 

Firestore supports nested subcollections, which can be beneficial for related data. Here’s how you can create a subcollection:

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

const db = getFirestore();
const userRef = doc(collection(db, 'users'), 'user-id');

// Create a subcollection named 'orders' within a specific user document.
const ordersCollection = collection(userRef, 'orders');

async function addOrder() {
  try {
    const orderRef = await addDoc(ordersCollection, {
      product: 'Laptop',
      quantity: 1,
    });
    console.log('Order added with ID: ', orderRef.id);
  } catch (e) {
    console.error('Error adding order: ', e);
  }
}

addOrder();

This example demonstrates how to:

  • Access a specific document.
  • Create a subcollection tied to that document.
  • Add data to the subcollection.

 

Step 5: Query Your Firestore Database

 

Querying data requires nuanced understanding to keep operations efficient. Firestore allows for structured queries. For instance:

import { query, where, getDocs } from 'firebase/firestore';

const q = query(usersCollection, where('name', '==', 'John Doe'));

async function getUsers() {
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((doc) => {
    console.log(`${doc.id} => `, doc.data());
  });
}

getUsers();

This snippet does the following:

  • Constructs a query to find documents where 'name' equals 'John Doe'.
  • Fetches documents from Firestore and logs each to the console.

 

Step 6: Consider Firestore Rules and Indexes

 

Once data structuring and querying is done, consider security and performance:

  • Security Rules: Define who can access or modify data.
  • Indexes: Behind the scenes, Firestore creates indexes to speed up queries. Consider your querying needs if additional composite indexes are necessary for your use cases.

By structuring data efficiently, using Firebase SDK's methods properly, and thinking ahead about security and performance, you set a robust foundation for Firestore operations in your application.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022