Skip to content

Firestore Write Operations — Complete Guide

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Firestore Write Operations. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Your Firestore write silently fails, or you overwrite an entire document when you only wanted to update one field.

Wrong Approach ❌

// Overwriting entire document — deletes fields not in the object!
val user = hashMapOf("name" to "Alice", "email" to "alice@example.com")
db.collection("users").document("user1").set(user)
// Any existing fields (e.g., "createdAt", "points") are DELETED!

Output: All existing fields are erased. Document now only has name and email.

Right Approach ✅

class UserRepository(private val db: FirebaseFirestore) {

    // Create or overwrite document
    suspend fun createUser(userId: String, user: User) {
        db.collection("users").document(userId)
            .set(user)
            .await()
    }

    // Update specific fields only — preserves other fields
    suspend fun updateUserName(userId: String, name: String) {
        db.collection("users").document(userId)
            .update("name", name)
            .await()
    }

    // Update multiple fields
    suspend fun updateUserProfile(userId: String, updates: Map<String, Any?>) {
        // Use field delete for removing fields
        val finalUpdates = updates.toMutableMap()
        if (updates.containsKey("removePhoto")) {
            finalUpdates["photoUrl"] = FieldValue.delete()
        }
        db.collection("users").document(userId)
            .update(finalUpdates)
            .await()
    }

    // Increment numeric field atomically
    suspend fun incrementScore(userId: String, points: Long) {
        db.collection("users").document(userId)
            .update("score", FieldValue.increment(points))
            .await()
    }

    // Add element to array
    suspend fun addToFavorites(userId: String, movieId: String) {
        db.collection("users").document(userId)
            .update("favorites", FieldValue.arrayUnion(movieId))
            .await()
    }

    // Server timestamp
    suspend fun touchLastLogin(userId: String) {
        db.collection("users").document(userId)
            .update("lastLogin", FieldValue.serverTimestamp())
            .await()
    }

    // Write with merge option — creates or updates without overwriting
    suspend fun upsertUser(userId: String, user: User) {
        db.collection("users").document(userId)
            .set(user, SetOptions.merge())
            .await()
    }
}

Output: Precise field updates without accidental overwrites.

Prevention

  • Use .update() for partial field updates, not .set().
  • Use SetOptions.merge() with .set() to avoid field deletion.
  • Use FieldValue.increment() for atomic counter operations.
  • Use FieldValue.serverTimestamp() for reliable timestamping.
  • Use FieldValue.arrayUnion()/arrayRemove() for array field updates.

Common Mistakes with firestore write

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between set() and update()?

set(data) overwrites the entire document. update(data) merges the provided fields with existing fields. set(data, SetOptions.merge()) behaves like update() but creates the document if it doesn't exist.

### How do I delete a field from a document?

Pass FieldValue.delete() as the field value in an update() call. The field is removed from the document on the server.

### Can I write to Firestore offline?

Yes. Firestore enables offline persistence by default. Writes are queued locally and synced when connectivity is restored. Listen to addSnapshotListener metadata for pending writes.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro