Home > front end >  Firestore: How to store data back again in the right documents after fetching data from multiple doc
Firestore: How to store data back again in the right documents after fetching data from multiple doc

Time:02-14

In my App a user can track his workouts, which I want to save in cloud firestore. My idea is to store a list of workouts for each month to prevent that a document gets too big. So a document would look something like this:

month: '2022-02',
workouts: [
  {
  date: '2022-02-01',
  exercises: [
       {
        sets: [{'reps': 12, 'weight': 80}
               {'reps': 12, 'weight': 80}
            ],
       },
     ],
 },
{
  date: '2022-02-02',
  exercises: [
       {
        sets: [{'reps': 10, 'weight': 90}
               {'reps': 10, 'weight': 90}
            ],
       },
     ],
 },
],

Question:

When I fetch for example the workouts from the last three month and put them in a list to let the user interact with these workouts. How can I store them again in cloud firestore sorted in the right month?

CodePudding user response:

To be able to write data back to the same document you read from, you will need to track the document ID for each piece of data in your list view, in addition to the fields you read from the document itself.

When you have the document ID, writing data to it is as easy as:

FirebaseFirestore.instance
  .collection("yourWorkoutsCollection")
  .document(documentIdForTheMonth)
  .update({ 'workouts': FieldValue.arrayUnion([theWorkoutToAdd]) });
  • Related