Firestore Write Operations — Complete Guide
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
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro