Home > Back-end >  How do I update each true key pair in a map in cloud firestore?
How do I update each true key pair in a map in cloud firestore?

Time:12-13

I’m working on an app with Flutter. Each of my users has a map with their to-dos stored in cloud firestore: enter image description here

I want to create a future that updates every to-do to false, which is true. (In my example, that would be ’sport' and ’eat healthy')


My Problem: I don’t really know how to do this. . .

I’d be very grateful if someone could help me.

CodePudding user response:

There is no magic solution here. With your current data model, the only approach is to:

  1. Read all documents
  2. Change any false todo's to `true
  3. Write back the document if you made any changes

The only way to make this cheaper (both in monetary cost as in the time it'll take) is to change #1 to only read documents that have a false value. In your current model that is only possible if To-Dos is an array, and then only for up to 10 values in there with an array-contains-any filter:

collectionRef.where("To-Dos", arrayContainsAny: [{
  "Drink Water": false,
  "Sport": false,
  "eat healthy": false
}]

If the keys in this field are entered by the user, the above may become unfeasible because you can only have up to 10 values in there. The solution in that case would be to change your data model to fit your needs (as is quite common when working with NoSQL databases). For example, you could store a simple top-level hasUncompletedTasks field that you update each time you also write the document, and then use that for the query.

CodePudding user response:

You want to set every field inside the To-Dos map to false which is true. So I would suggest updating every field to false. You might think of checking if it is true and then updating it. But for your use case it is not a good option as anyway you want to set every field to false. Checking and then updating will only incur extra charges for querying. The following should work for your use case.

CollectionReference users = FirebaseFirestore.instance.collection('users');

Future<void> updateUserToDos() {
 return users
     .doc('your_document_id')
     .update({
       'To-Dos.Drink Water': false,
       'To-Dos.Sport': false,
       'To-Dos.eat healthy': false
     })
     .then((value) => print("User To-Dos Updated"))
     .catchError((error) => print("Failed to update user: $error"));
}

To know more about updating document fields of Firestore in Flutter you can refer to this document.

  • Related