I want to update one field and, in some case, another field of the same document in a batch:
db.runBatch { batch ->
val myRef = db.document("path/to/document")
batch.update(myRef, "foo", "bar")
if(someCondition) {
batch.update(myRef, "baz", "bar")
}
}
Is this billed as a single write or as two writes in case someCondition
is true?
As an alternative I could do something like this:
db.runBatch { batch ->
val myRef = db.document("path/to/document")
if(someCondition) {
batch.update(myRef, "foo", "bar", "baz", "bar")
} else {
batch.update(myRef, "foo", "bar")
}
}
But that leads to duplicating code and becomes very messy in case of updating more fields
It should be only one write, but this is very easy to work around if you don't have confidence in that. Just take a different approach where you build the Map of updates just once, and pass the to update() which takes a Map:
db.runBatch { batch ->
val myRef = db.document("path/to/document")
val obj = if (someCondition) {
mapOf("foo" to "bar", "baz" to "bar")
}
else {
mapOf("foo" to "bar")
}
batch.update(myRef, obj)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With