who-aditya-nawandar
who-aditya-nawandar

Reputation: 1344

Flutter - How to add(create) a nested collection first time and then add fields(update the collection) next time in Firestore

In this method I create a new collection("workouts") the first time a set(exercise set) is saved. A workout will have multiple exercises. So how do I add the next exercises to the same workout?

_saveExerciseSetForUser() {
if (currentUser != null) {
  FirebaseFirestore.instance
      .collection('users')
      .doc(currentUser!.uid)
      .collection("workouts")
      .doc()
      .collection("exercises")
      .doc(exerciseId)
      .collection("sets")
      .doc()
      .set({
    
    "setNo.": setCount,
    "weight": weightController.text,
    "reps": repsController.text,
    "toFailure": false
  }).then((value) => {
    
  });
 }
}

Upvotes: 1

Views: 195

Answers (1)

mrgnhnt96
mrgnhnt96

Reputation: 3945

In order to add new exercises to existing workouts, you'll need to keep track of the doc or it's ID for your workout. Once you have the workout ID, you will know the path that you can add the new exercise to. users/$userId/workouts/$workoutId/exercises/$exerciseId/sets

Future<void> _saveExerciseSetForUser([String? workoutId]) async {
  if (currentUser == null) {
    return;
  }

  final data = {
    "setNo.": setCount,
    "weight": weightController.text,
    "reps": repsController.text,
    "toFailure": false,
  };

  final workoutDoc = FirebaseFirestore.instance
    .collection('users')
    .doc(currentUser!.uid)
    .collection("workouts")
    // if workoutId is null, this will create a new workout
    .doc(workoutId);

  // save doc id somewhere
  final workoutDocId = workoutDoc.id;

  await workoutDoc.collection("exercises")
    .doc(exerciseId)
    .collection("sets")
    .doc()
    .set(data);
}

Upvotes: 1

Related Questions