/firebase-tutorials

How to store arrays in Firestore?

Learn how to store, update, and retrieve arrays in Firestore with this step-by-step Firebase tutorial featuring practical code examples and edge-case tips.

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 store arrays in Firestore?

Here's a comprehensive, detailed, and specific step-by-step tutorial on storing arrays in Firestore.

 

Step 1: Set Up Firebase in Your Project

 

To start using Firestore in your project, you need to set up Firebase. First, go to the Firebase Console and create a new project or select an existing one.

Then, to set up Firebase in your web application, add the Firebase configuration to your project. This usually involves installing Firebase using npm or adding the Firebase SDK via a CDN.

If you're using npm, run the following command in your project directory:

npm install firebase

Then, initialize Firebase in your project:


import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "your-api-key",
  authDomain: "your-auth-domain",
  projectId: "your-project-id",
  storageBucket: "your-storage-bucket",
  messagingSenderId: "your-messaging-sender-id",
  appId: "your-app-id"
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

 

Step 2: Structure Your Firestore Database

 

Decide on the structure for storing arrays. Firestore is a NoSQL database, which means it uses documents to store data instead of tables. Within each document, you can have fields which can include arrays.

For example, let's say you want to store a list of favorite movies for users. You might have a collection called users, and each document within the collection represents a user. Each user document can include a field for an array of favorite movies.

 

Step 3: Add Data with Arrays to Firestore

 

To add a document to Firestore with an array field:


import { doc, setDoc } from "firebase/firestore"; 

async function addUserWithMovies(userId, moviesArray) {
  try {
    await setDoc(doc(db, "users", userId), {
      favoriteMovies: moviesArray
    });
    console.log("Document successfully written!");
  } catch (e) {
    console.error("Error writing document: ", e);
  }
}

// Usage
addUserWithMovies("user123", ["Inception", "The Matrix", "Interstellar"]);

 

Step 4: Update Array Data in Firestore

 

Firestore provides methods to update arrays. You can add to an array field using arrayUnion and remove using arrayRemove.

For example, to add a new movie:


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

async function addMovieToUser(userId, newMovie) {
  const userRef = doc(db, "users", userId);

  try {
    await updateDoc(userRef, {
      favoriteMovies: arrayUnion(newMovie)
    });
    console.log("Movie added successfully!");
  } catch (e) {
    console.error("Error adding movie: ", e);
  }
}

// Usage
addMovieToUser("user123", "Tenet");

Similarly, to remove a movie from the array:


import { arrayRemove } from "firebase/firestore";

async function removeMovieFromUser(userId, movieToRemove) {
  const userRef = doc(db, "users", userId);

  try {
    await updateDoc(userRef, {
      favoriteMovies: arrayRemove(movieToRemove)
    });
    console.log("Movie removed successfully!");
  } catch (e) {
    console.error("Error removing movie: ", e);
  }
}

// Usage
removeMovieFromUser("user123", "The Matrix");

 

Step 5: Retrieve Array Data from Firestore

 

To retrieve the document and access the array field, you can use the getDoc method:


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

async function getUserMovies(userId) {
  const userRef = doc(db, "users", userId);
  
  try {
    const userSnap = await getDoc(userRef);
    
    if (userSnap.exists()) {
      console.log("User data:", userSnap.data().favoriteMovies);
    } else {
      console.log("No such document!");
    }
  } catch (e) {
    console.error("Error fetching document: ", e);
  }
}

// Usage
getUserMovies("user123");

 

Step 6: Handling Edge Cases

 

When dealing with arrays in Firestore, ensure you handle edge cases such as:

  • Empty arrays: Make sure your logic can handle cases where the array might be empty.
  • Unique values: If you want to ensure that the array elements are unique, you will need to implement additional checks, as arrayUnion only adds elements if they are not already present.
  • Data size limits: Firestore has a limit on the size of documents. Arrays within documents should be managed to avoid hitting these limits.

By following these steps, you can efficiently store and manage arrays within Firestore using Firebase's powerful tools and methods.

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