0
0
Firebasecloud~3 mins

Why Array update operations (arrayUnion, arrayRemove) in Firebase? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could update lists in your database with one simple command, no mistakes, no delays?

The Scenario

Imagine you have a list of favorite movies stored in your app's database. You want to add a new movie or remove one without messing up the list or accidentally deleting other movies.

Doing this by hand means fetching the whole list, changing it, and saving it back. This can be tricky and slow, especially if many users do it at the same time.

The Problem

Manually updating lists is slow because you must read the entire list, change it, then write it back.

This causes delays and risks overwriting others' changes if many users update at once.

It's easy to make mistakes like adding duplicates or removing the wrong item.

The Solution

Array update operations like arrayUnion and arrayRemove let you add or remove items directly on the server.

This means you don't have to fetch the whole list or worry about duplicates or conflicts.

The database handles it safely and quickly for you.

Before vs After
Before
let favorites = doc.data().movies;
favorites.push('New Movie');
db.doc('user/123').update({movies: favorites});
After
db.doc('user/123').update({movies: firebase.firestore.FieldValue.arrayUnion('New Movie')});
What It Enables

You can safely and quickly add or remove items from lists in your database without extra code or errors.

Real Life Example

A music app lets users add songs to their playlist. Using arrayUnion, the app adds new songs without duplicates, even if many users add songs at the same time.

Key Takeaways

Manual list updates are slow and error-prone.

arrayUnion and arrayRemove update lists safely on the server.

This makes your app faster and more reliable when changing lists.