📖 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
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
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
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
Hint
Add await updateDoc(userDocRef, { favoriteGenres: arrayRemove('Romance') }); after the existing update.
Practice
(1/5)
1. What does the arrayUnion operation do in Firebase Firestore?
easy
A. Removes all elements from an array field
B. Adds unique elements to an array field without duplicates
C. Replaces the entire array with a new one
D. Sorts the array elements in ascending order
Solution
Step 1: Understand arrayUnion purpose
The arrayUnion operation adds elements to an array field only if they are not already present, ensuring no duplicates.
Step 2: Compare with other options
The other options describe removing all elements, replacing the array, or sorting, which are not what arrayUnion does.
Final Answer:
Adds unique elements to an array field without duplicates -> Option B
Quick Check:
arrayUnion adds unique items without duplicates [OK]
Hint: arrayUnion only adds new unique items to arrays [OK]
Common Mistakes:
Thinking arrayUnion removes items
Confusing arrayUnion with replacing arrays
Assuming arrayUnion sorts the array
2. Which of the following is the correct syntax to add an element 'blue' to an array field 'colors' using arrayUnion in Firestore?
easy
A. docRef.update({ colors: arrayUnion('blue') })
B. docRef.update({ colors: arrayRemove('blue') })
C. docRef.set({ colors: arrayUnion('blue') })
D. docRef.add({ colors: arrayUnion('blue') })
Solution
Step 1: Identify correct method for updating fields
To update an existing document's field, update() is used, not set() or add().
Step 2: Use arrayUnion to add element
The syntax arrayUnion('blue') correctly adds 'blue' to the array without duplicates.
Final Answer:
docRef.update({ colors: arrayUnion('blue') }) -> Option A
Quick Check:
Use update() with arrayUnion() to add items [OK]
Hint: Use update() with arrayUnion() to add array items [OK]
Common Mistakes:
Using arrayRemove instead of arrayUnion
Using set() which overwrites the whole document
Using add() which is for collections, not fields
3. Given the Firestore document field tags: ['news', 'tech'], what will be the value of tags after this update?
Step 1: Understand arrayUnion behavior with existing elements
arrayUnion adds only new unique elements. 'tech' already exists, so it won't be duplicated.
Step 2: Add new element 'science'
'science' is new, so it will be added to the array.
Final Answer:
['news', 'tech', 'science'] -> Option A
Quick Check:
arrayUnion adds only new unique items [OK]
Hint: arrayUnion skips duplicates, adds only new items [OK]
Common Mistakes:
Expecting duplicates to be added
Thinking arrayUnion removes items
Confusing arrayUnion with arrayRemove
4. You want to remove the string 'urgent' from the array field 'labels' in a Firestore document. Which code snippet contains an error?
medium
A. docRef.update({ labels: arrayRemove('urgent', 'important') })
B. docRef.update({ labels: arrayRemove(['urgent']) })
C. docRef.update({ labels: arrayRemove() })
D. docRef.update({ labels: arrayRemove('urgent') })
Solution
Step 1: Check valid usage of arrayRemove
arrayRemove requires at least one argument specifying which elements to remove.
Step 2: Analyze each option
docRef.update({ labels: arrayRemove() }) calls arrayRemove with no arguments, which is invalid and causes an error. docRef.update({ labels: arrayRemove(['urgent']) }) attempts to remove the array ['urgent'] (won't match/remove string 'urgent'). docRef.update({ labels: arrayRemove('urgent', 'important') }) removes both if present. docRef.update({ labels: arrayRemove('urgent') }) correctly removes 'urgent'.
Final Answer:
docRef.update({ labels: arrayRemove() }) -> Option C
Quick Check:
arrayRemove needs at least one element argument [OK]
Hint: arrayRemove must have at least one element argument [OK]
Common Mistakes:
Calling arrayRemove with no arguments
Passing an array inside arrayRemove instead of elements
Confusing arrayRemove with arrayUnion
5. You have a Firestore document with an array field participants: ['alice', 'bob', 'carol']. You want to update it so that 'bob' is removed and 'dave' is added, ensuring no duplicates. Which update code achieves this?
hard
A. docRef.update({ participants: arrayRemove('bob'), participants: arrayUnion('dave') })
B. docRef.update({ participants: arrayRemove('bob', 'dave') })
C. docRef.update({ participants: arrayUnion('dave') })
D. docRef.update({ participants: arrayRemove('bob') }); docRef.update({ participants: arrayUnion('dave') })
Solution
Step 1: Understand Firestore update limitations
You cannot apply both arrayRemove and arrayUnion to the same field in a single update object (duplicate keys overwrite, only last applies).
Step 2: Analyze options
docRef.update({ participants: arrayRemove('bob'), participants: arrayUnion('dave') }): duplicate keys, only arrayUnion('dave') applies (adds 'dave', keeps 'bob'). docRef.update({ participants: arrayRemove('bob', 'dave') }): removes 'bob' ('dave' ignored since absent), no add. docRef.update({ participants: arrayUnion('dave') }): adds 'dave', no remove. docRef.update({ participants: arrayRemove('bob') }); docRef.update({ participants: arrayUnion('dave') }): first removes 'bob', then adds 'dave' -> ['alice', 'carol', 'dave'].