/firebase-tutorials

How to model relationships in Firestore?

Learn how to model Firestore relationships with a step-by-step guide on one-to-one, one-to-many, and many-to-many patterns using Firebase.

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 model relationships in Firestore?

 

Step 1: Setting Up Firebase Project

 

  1. Create a Firebase Project
  • Go to the Firebase Console.
  • Click on "Add project" and follow the instructions to set up your Firebase project.
  • Enable Firestore Database in the Firebase console under "Build" > "Firestore Database".
  1. Integrate Firebase into Your Application
  • Follow instructions under "Project settings" > "General" to add Firebase to your app.
  • Download the google-services.json file for Android or GoogleService-Info.plist for iOS and place it in the appropriate directory of your application project.
  1. Install Firebase SDK in Your Application
  • For Web:
    ```html ```
  • For Android:
    ```groovy
    dependencies {
    implementation platform('com.google.firebase:firebase-bom:30.3.1')
    implementation 'com.google.firebase:firebase-firestore-ktx'
    }
    ```
  • For iOS:
    ```swift
    pod 'Firebase/Firestore'
    ```

 

Step 2: Designing the Data Model

 

  • Understand Firestore’s Structure
    Firestore is a NoSQL database that stores data in documents, which are organized into collections. Each document contains a set of key-value pairs and each document is identified by a unique ID.

  • Modeling One-to-One Relationships
    Suppose you have two collections, Users and their Profiles. Each user has one profile.

  • In Users collection, store a reference to the corresponding Profiles document.

    ```json
    {
    "userId": "abc123",
    "profileRef": "Profiles/profileId123"
    }
    ```

  • Modeling One-to-Many Relationships
    Suppose, each User can have multiple Posts.

  • Embed Post IDs within each user document, or keep Post documents in the Posts collection with a userId field.

    ```json
    {
    "userId": "abc123",
    "posts": ["postId1", "postId2"]
    }
    ```

    Or in separate collection with reference:

    ```json
    {
    "postId": "postId1",
    "userId": "abc123",
    "content": "This is a post"
    }
    ```

  • Modeling Many-to-Many Relationships
    For example, Users and Groups, where each user can be in multiple groups and vice versa.

  • Use sub-collections or embedding arrays of references:

    In Users:

    ```json
    {
    "userId": "abc123",
    "groups": ["groupId1", "groupId2"]
    }
    ```

    In Groups:

    ```json
    {
    "groupId": "groupId1",
    "members": ["userId1", "userId2"]
    }
    ```

 

Step 3: Writing Data with Relationships

 

  • Add a Document with a Reference

  • Import necessary modules and write data to Firestore with JavaScript SDK.
    ```javascript
    import { doc, setDoc } from "firebase/firestore";

    // Reference to a user
    const userRef = doc(db, 'Users', 'userId123');
    await setDoc(userRef, {
    profileRef: 'Profiles/profileId123'
    });
    ```

  • Add Documents with Sub-collections

  • For Posts sub-collection under Users.
    ```javascript
    import { collection, addDoc } from "firebase/firestore";

    // Reference to posts sub-collection
    const postsRef = collection(db, 'Users/userId123/Posts');
    await addDoc(postsRef, {
    content: 'This is a user post'
    });
    ```

 

Step 4: Reading Data with Relationships

 

  • Retrieve a Document with a Sub-collection
    Retrieve the user document and associated posts sub-collection.

    ```javascript
    import { collection, getDocs } from "firebase/firestore";

    // To get posts for a specific user
    const querySnapshot = await getDocs(collection(db, 'Users/userId123/Posts'));
    querySnapshot.forEach((doc) => {
    console.log(${doc.id} => ${doc.data()});
    });
    ```

  • Retrieve a Document with References
    Fetch a user and then fetch the profile document by its reference.

    ```javascript
    import { doc, getDoc } from "firebase/firestore";

    const userRef = doc(db, 'Users', 'userId123');
    const userSnap = await getDoc(userRef);

    if (userSnap.exists()) {
    const profileRef = doc(db, userSnap.data().profileRef);
    const profileSnap = await getDoc(profileRef);
    console.log('Profile:', profileSnap.data());
    }
    ```

 

Step 5: Updating Relationships in Firestore

 

  • Update a Simple Field or Reference
    Use the updateDoc method to update a reference or field in your document.

    ```javascript
    import { updateDoc, doc } from "firebase/firestore";

    const userRef = doc(db, 'Users', 'userId123');
    await updateDoc(userRef, {
    profileRef: 'Profiles/profileId456'
    });
    ```

  • Handling Arrays in Firestore
    Firestore supports operations like arrayUnion and arrayRemove for handling array fields.

    ```javascript
    import { updateDoc, arrayUnion, doc } from "firebase/firestore";

    const groupRef = doc(db, 'Groups', 'groupId1');
    await updateDoc(groupRef, {
    members: arrayUnion('userId3')
    });
    ```

 

Step 6: Deleting Relationships

 

  • Delete a Sub-collection Document
    To delete a document within a sub-collection, use the deleteDoc method.

    ```javascript
    import { doc, deleteDoc } from "firebase/firestore";

    await deleteDoc(doc(db, 'Users/userId123/Posts', 'postId456'));
    ```

  • Remove a Reference from a Document
    Either update the field to null or use arrayRemove on an array of references.

    ```javascript
    import { updateDoc, arrayRemove, doc } from "firebase/firestore";

    const userRef = doc(db, 'Users', 'userId123');
    await updateDoc(userRef, {
    groups: arrayRemove('groupId1')
    });
    ```

 

By following these steps, you can effectively model and manage relationships in Firestore. Understanding and properly designing your data model is crucial to optimize both the performance and scalability of 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