简体   繁体   中英

Loop through all firestore documents in a collection AND update them in flutter

I need to iterate through all the documents in the "exercise" collection and update them with new values. I wrote a function that works but it's an inefficient solution. This is the whole function:

final thisWorkout = await FirebaseFirestore.instance
  .collection('workouts')
  .doc(widget.docRef!.id);

final allExercises = await thisWorkout.collection('exercise').get();

thisWorkout.update({
    'name': workoutName,
  });

  List allIds = [];

  allExercises.docs.forEach((DocumentSnapshot value) {
    allIds.add(value.reference.id);
  });

  for (var i = 0; i < exercises.length; i++) {
    thisWorkout.collection('exercise').doc(allIds[i]).set(exercises[i]);
  }

This is the portion of the function that is inefficient:

List allIds = [];

  allExercises.docs.forEach((DocumentSnapshot value) {
    allIds.add(value.reference.id);
  });

  for (var i = 0; i < exercises.length; i++) {
    thisWorkout.collection('exercise').doc(allIds[i]).set(exercises[i]);
  }

Is there a way to just iterate through each doc AND update it without having store all the ids then run a separate for loop for the update?

You mean this?

allExercises.docs.forEach((DocumentSnapshot value) {
  thisWorkout.collection('exercise').doc(value.reference.id).set(exercises[i]);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM