0
0
Firebasecloud~30 mins

Array update operations (arrayUnion, arrayRemove) in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Array update operations (arrayUnion, arrayRemove)
📖 Scenario: You are managing a Firestore database for a book club app. Each user document has a list of favorite book genres stored as an array. You want to update this array by adding new genres without duplicates and removing genres the user no longer likes.
🎯 Goal: Build Firestore update commands using arrayUnion and arrayRemove to add and remove genres from a user's favorite genres array.
📋 What You'll Learn
Create a reference to the Firestore document for user with ID 'user123'.
Add the genres 'Mystery' and 'Science Fiction' to the user's favorite genres array using arrayUnion.
Remove the genre 'Romance' from the user's favorite genres array using arrayRemove.
Use valid Firestore update syntax with updateDoc and import the necessary Firestore functions.
💡 Why This Matters
🌍 Real World
Managing user preferences or tags in Firestore is common in apps like book clubs, social media, or e-commerce. Using array update operations keeps data consistent and avoids duplicates.
💼 Career
Understanding Firestore array operations is essential for cloud developers working with Firebase to build scalable and user-friendly applications.
Progress0 / 4 steps
1
Set up Firestore document reference
Import doc from firebase/firestore and create a document reference called userDocRef for the user with ID 'user123' in the collection 'users'.
Firebase
Need a hint?

Use doc(db, 'users', 'user123') to get the document reference.

2
Import array update functions
Import updateDoc, arrayUnion, and arrayRemove from firebase/firestore to prepare for updating the array fields.
Firebase
Need a hint?

Import all needed functions in one statement for clarity.

3
Add genres using arrayUnion
Write an updateDoc call on userDocRef that adds the genres 'Mystery' and 'Science Fiction' to the favoriteGenres array using arrayUnion.
Firebase
Need a hint?

Use updateDoc with an object where the key is favoriteGenres and the value is arrayUnion('Mystery', 'Science Fiction').

4
Remove genre using arrayRemove
Add another updateDoc call on userDocRef to remove the genre 'Romance' from the favoriteGenres array using arrayRemove.
Firebase
Need a hint?

Add await updateDoc(userDocRef, { favoriteGenres: arrayRemove('Romance') }); after the existing update.