0

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 !

SNM
  • 5,625
  • 9
  • 28
  • 77

2 Answers2

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.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • thanks doug, I'm thinking of getting all the array, update just one element and then set again all the array in the same array node but now with the updated array field, is that ok ? – SNM Apr 18 '20 at 22:54
0

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)
    }
SNM
  • 5,625
  • 9
  • 28
  • 77