问题
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