0

So I am creating an attendance app in which there is a list named attendees which contains the list of all students attending the lecture.

List<String> attendees = [uid0, uid1, uid2];

and the student data model is as follows

Student(
List<String> attendance = [at0, at1]; //this is the list of lectures attended
String name;
)

and the document name of every student is their user-id
How do I update the list of every student via the batch() function?

2
  • Is this by any means related to this question? Or is the similarity of the data structures just coincidence? Commented Mar 4, 2022 at 22:31
  • No, it is not related to it Commented Mar 4, 2022 at 22:42

1 Answer 1

1

I assume you already have a list of attendees that contains user-id as you mentioned the userId would be the documentId in Firestore.

Therefore, you can do a loop and update your doc directly and then use commit to apply your changes.

updateBatch(List<String> attendees) async {
  try {
    final db = FirebaseFirestore.instance;

    final WriteBatch batch = db.batch();

    // based on this doc https://firebase.flutter.dev/docs/firestore/usage/#batch-write
    // Each transaction or batch of writes can write to a maximum of 500 documents.
    for (final userid in attendees) {
      // Use the batch to update a document that exist otherwise it will throw error,
      // in case you want to create that doc, maybe you should use `set` instead
      // ref: https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/WriteBatch/update.html
      batch.update(
        //Give the ref of document.
        db.document('Path/to/firestore/document'),  // e.g: /Students/userId
        //And the data to update.
        {"key": value},
      );
    }

    await batch.commit();
    print('success');
  } catch (e) {
    print('error $e');
  }
}

A few notes:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.