0

How can I modify in the single item the value of a single field, for example, the id, and leave all the other fields at the initial value without having to delete and reinsert the item?

Firestore DB

2 Answers 2

2

It may be late to answer but here is the solution

val washingtonRef = db.collection("cities").document("DC")

// Atomically add a new region to the "regions" array field.
washingtonRef.update("regions", FieldValue.arrayUnion("greater_virginia"))

// Atomically remove a region from the "regions" array field.
washingtonRef.update("regions", FieldValue.arrayRemove("east_coast"))

Here is the link you can also read

https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to modify individual objects of an array type field, you have to read the document, modify the array on the client, then update the modified array back to the document in Firestore.

Please note, that you cannot do that without reading the document first. Assuming that you have a data class that looks like this:

data class Place(
    var id: String? = null,
    var isCancelled: Boolean? = null,
    var price: String? = null,
    var reservationName: String? = null,
    var reservationPhone: String? = null,
)

For reading the array of objects, the simplest method I can think of is to get the array as a list of "Place" objects (List<Place>) and right after that update the desired element according to your needs.

3 Comments

Hi Alex. I liked your article that you linked to. I've posted a question about dealing with enums. As you seem to be a seasoned expert, I was wondering if you had any ideas?
@Zonker.in.Geneva I'm not sure about which question you are referring to. But if you one, please post a new question, here on StackOverflow, using its own MCVE, so I and other Firebase developers can help you.
I did post here on SO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.