0

Hi I have 2 Firestore collections named

  1. products collection
  2. category collection

when creating a document in the products collection, it adds a field name category which we get from a document in the category collection. (Simply when making a product we have to choose a category name from the category collection).

So far I have implemented this successfully. But now my problem is when changing the name field in a category document (changing category name/title), it changes to the new name in the category document but stays the same in the product document (since not notifying the category name change to related product documents).

For changing the category name I use the following code

  Future<void> updateCategory({Key? key,cid,name}) {
     return categories
    .doc(uid).collection('categoryList').doc(cid)
    .update({'name': name})
    .then((value) => print("Category Updated"))
    .catchError((error) => print("Failed to update category: $error"));}

How can I update the category name field in product documents, when I change the category name from the category collection?

  • You can try transactions as discussed in this [thread](https://stackoverflow.com/q/74242825/18265570) and also check [this](https://stackoverflow.com/q/47254978/18265570) – Roopa M Feb 07 '23 at 15:25

1 Answers1

1

There is no specific operation to update the duplicated data. You will need to update each product document in turn. Typically this takes something like:

  1. Use a query to find all the product documents
  2. Loop through the query snapshot
  3. Update each individual product document

If you have a lot of documents to update, consider What is the fastest way to write a lot of documents to Firestore?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807