简体   繁体   中英

How to update data in an array of objects in Firestore using Kotlin?

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 数据库

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM