Firestore Partial Update: Create Document if Not Exist

May 18, 2019

To perform partial update on new/existing document, use set with SetOptions.merge()

docRef.set(mapOf(    "name" to "Partial replace"), SetOptions.merge())

Create a kotlin extension for updateOrCreate.

fun DocumentReference.updateOrCreate(data: Any): Task<Void> {    return set(data, SetOptions.merge())}

NOTE: Beware there are some bahavior difference between set with SetOptions.merge() vs update for update map and updated nested field.

Update Fail if document does not exist.

Use update for partial update.

docRef.update(mapOf(    "name" to "Partial replace"))

The update will fail if applied to a document that does not exist.

with the following error.

java.util.concurrent.ExecutionException: com.google.firebase.firestore.FirebaseFirestoreException: NOT_FOUND: No document to update

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.