0
0
FirebaseHow-ToBeginner · 3 min read

How to Update a Document in Firestore: Simple Guide

To update a document in Firestore, use the update() method on a document reference with the fields you want to change. This method changes only the specified fields without overwriting the entire document.
📐

Syntax

The update() method is called on a Firestore document reference. You pass an object with the fields and new values you want to update.

  • docRef: Reference to the document you want to update.
  • updateData: An object with key-value pairs for fields to update.
javascript
updateDoc(docRef, { field1: newValue1, field2: newValue2 })
💻

Example

This example updates the age and city fields of a user document in Firestore.

javascript
import { initializeApp } from 'firebase/app';
import { getFirestore, doc, updateDoc } from 'firebase/firestore';

const firebaseConfig = {
  // your config here
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

async function updateUser() {
  const userRef = doc(db, 'users', 'user123');
  try {
    await updateDoc(userRef, {
      age: 30,
      city: 'New York'
    });
    console.log('Document updated successfully');
  } catch (error) {
    console.error('Error updating document:', error);
  }
}

updateUser();
Output
Document updated successfully
⚠️

Common Pitfalls

Common mistakes when updating Firestore documents include:

  • Using set() instead of update() which overwrites the whole document.
  • Trying to update a document that does not exist, which causes an error.
  • Passing incorrect field names or data types.

Always ensure the document exists before updating or handle errors properly.

javascript
/* Wrong: overwrites entire document */
docRef.set({ age: 30 });

/* Right: updates only specified fields */
updateDoc(docRef, { age: 30 });
📊

Quick Reference

Tips for updating Firestore documents:

  • Use update() to change specific fields without deleting others.
  • Use set() with { merge: true } to merge fields safely.
  • Handle errors to catch missing documents or permission issues.

Key Takeaways

Use update() to modify specific fields without overwriting the whole document.
Ensure the document exists before updating to avoid errors.
Handle errors to manage permission or existence issues gracefully.
Use set() with { merge: true } if you want to merge fields safely.
Always pass correct field names and data types in the update object.