I need to update a certain array entry of my Map in Firestore

烂漫一生 提交于 2021-02-11 15:40:55

问题


I want to update a product of my products array.

I have an array of products in a collection

products[{
   - 0
   productPrice: 123
   - 1
   productPrice: 432
}]

In my code I have passed the position of the element I want to update in that array of products

  suspend fun updateProductPrice(position:Int,shopId: String,price: Int): Resource<Unit> {
        FirebaseFirestore.getInstance().collection("shops").document(shopId).update("products"[position]) //here I need to get productPrice and update its value to the price parameter in my method
        return Resource.Success(Unit)
    }

I need to update that productPrice (at the position 0) value whiting that array, but I dont find how

Thanks !


回答1:


It's not possible to update arrays by their index. You will have to read the document, modify the array in memory the way you want, then update the array field back to the document. You can use a transaction if you need the operation to be atomic.




回答2:


I have solved my issue as doug said, I have edited the element in my array that needed a price change, then I just update the whole array of data with all the array but with the one entry at my desired position updated, here is how I did it

 suspend fun updateProductPrice(position:Int,shopId: String,price: Int,productList:MutableList<Product>): Resource<Unit> {
        productList[position].price = price
        FirebaseFirestore.getInstance().collection("shops").document(shopId).update("products",productList).await()
        return Resource.Success(Unit)
    }


来源:https://stackoverflow.com/questions/61297047/i-need-to-update-a-certain-array-entry-of-my-map-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!