2

Screenshot of my Firestore database structure

How to access and update a specific field in flutter fireStore Database?

Future<void> updateMyOrder(String username, String status) => FirebaseFirestore.instance
  .collection("checkout")
  .doc(username)
  .update({'cart.condition': status});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
steve
  • 23
  • 9
  • What is wrong with your current implementation? – Josteve May 15 '22 at 10:47
  • if you look at the screenshot, the 'cart' is a List of Map. And I want to update a specific field under 'cart' > 'condition', but it rather override the current data in the collection – steve May 15 '22 at 11:48
  • In the screen shot link, I have circled the field i need to update, but it overrides the existing data(List of Maps) – steve May 15 '22 at 11:56

1 Answers1

1

There is no field cart.condition in the document you show, as that'd be a map-field called cart with a subfield called condition in it.

I think you're trying to update a field of an array item, which is not possible in Firestore. The only array operations are array-union, which adds a new item to an array if it's not already in there, and array-remove. Both of these require that you specify the entire array item, and not just one/some fields of it.

The only way to update a field in a Firestore document is to:

  1. Load the document in your application code.
  2. Get the entire array from it.
  3. Modify the item in the array.
  4. Write the entire array back to the database.
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • ooo ok. Meaning that, Firestore doesn't supporting updating array elements by its index. Hence I need to read the entire document and modify the array in memory, then set or update the entire array docs...thank you Frank – steve May 15 '22 at 14:45
  • _your recommended approach was succesfully... **thank you**_. **Below is the successful code** `Future updateMyOrder(String username, Map oldData) { DocumentReference ref = FirebaseFirestore.instance.collection("checkout").doc(username); return ref.update({ 'cart': FieldValue.arrayRemove([oldData]) }).then((value) { oldData.update('condition', (val) => oldData['condition'] == 'new' ? 'old' : 'new'); return ref.update({ 'cart': FieldValue.arrayUnion([oldData]) }); }); }` – steve May 15 '22 at 15:57