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.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
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:
arrayUnion only adds elements if they are not already present.By following these steps, you can efficiently store and manage arrays within Firestore using Firebase's powerful tools and methods.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.