0
0
Firebasecloud~3 mins

Adding documents (add vs set) in Firebase - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how a simple choice can save your data from being lost or overwritten!

The Scenario

Imagine you have a notebook where you write down important notes. You want to add a new note, but you have to decide whether to write it on a new page automatically or choose a specific page yourself.

The Problem

Manually choosing pages or writing notes can be confusing and slow. You might accidentally overwrite an existing note or waste time finding a free page. This causes mistakes and frustration.

The Solution

Using 'add' lets the system pick a new page for your note automatically, so you never overwrite anything. Using 'set' lets you choose exactly where to write, giving you control when you need it.

Before vs After
Before
db.collection('notes').doc('note1').set({text: 'Hello'})
After
db.collection('notes').add({text: 'Hello'})
What It Enables

This choice lets you easily add new data safely or update specific data exactly as you want.

Real Life Example

When saving user messages, 'add' quickly creates new entries without conflicts. When updating user profiles, 'set' updates the exact record you want.

Key Takeaways

'add' creates new documents with unique IDs automatically.

'set' writes data to a specific document ID you choose.

Choosing the right method prevents data loss and saves time.