0
0
GcpHow-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 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: Object containing key-value pairs of fields to update.
javascript
docRef.update({ field1: newValue1, field2: newValue2 });
💻

Example

This example shows how to update 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, causing 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 */
docRef.update({ age: 30 });
📊

Quick Reference

MethodDescription
update()Updates specified fields without overwriting the whole document.
set(data, { merge: true })Merges data with existing document, similar to update but creates document if missing.
set(data)Overwrites entire document with new data.

Key Takeaways

Use update() to change only specific fields in a Firestore document.
update() fails if the document does not exist; handle errors accordingly.
Avoid set() without merge option to prevent overwriting the whole document.
Always pass an object with field-value pairs to update().
Check your field names and data types to avoid update errors.