How to Get, change, and Set a field from Firestore in a document?

131

There is no atomic operation to update all documents in one go. Since your new value depends on the existing value, you will need to:

  1. Read all documents from the collection.

  2. Loop through them one by one in your application code.

  3. Calculate the new value for each document, and write that back to the database.

Share:
131
MakeApps
Author by

MakeApps

Updated on January 04, 2023

Comments

  • MakeApps
    MakeApps 10 months

    I have a scheduling app and one of my properties is DateTime. I want to be able to "push back" or "pull forwards" all timestamps, in hours/minutes, through user input. My problem is when trying to use my PushPull method, it requires an instance of DocumentSnapshot, which I don't know how to instantiate.

    I have four text fields for pushing/pulling hours/minutes that look like this:

            TextField( controller: pullHourController,
     decoration: const InputDecoration(hintText: 'Hours'),
        onChanged: (newValue) =>
        pullHourController.setSelected(newValue),),
    

    Then I parse the String to ints like:

    late int pullHour = int.parse(pullHourController.text);
    

    and my pushpull method I put on a button:

    CollectionReference products =
          FirebaseFirestore.instance.collection('products');
    
    Future pushPull(DocumentSnapshot documentSnapshot) async {
        Timestamp timestamp = await documentSnapshot.get('Start Time');
        late DateTime d = timestamp.toDate();
        late DateTime added = DateTime(d.year, d.month, d.day,
            d.hour - pullHour + pushHour, d.minute - pullMinute + pushMinute);
    
        await products.doc().set({'Start Time': added}).catchError((error) =>
            {Get.snackbar("Failed to change time: $error", 'Please try again.')});
    
        throw (e) => Get.snackbar('Error', (e).toString());
      }
    

    However, when I try to use this in my onPressed, I need a documentSnapshot as a positional argument, but it isn't locally available:

    onPressed: () async {
                          pushPull();
                        },
    

    I've tried getting rid of the brackets like pushPull but nothing happens when its clicked.

    • Frank van Puffelen
      Frank van Puffelen over 1 year
      Since you want to update an existing document, you'll need to know the ID of the document you want to update. Do you know that? Can you show it in the code in your question?
    • MakeApps
      MakeApps over 1 year
      @FrankvanPuffelen Hi I'm trying to update all documents in the 'products' collection. They all hold the 'start time' field.
  • MakeApps
    MakeApps over 1 year
    Definitely didn't expect a cloud employee to help me with my first question. You just saved me from another 8 hours of headache, thank you!