anchxt
anchxt

Reputation: 47

How to batch update arrays?

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?

Upvotes: 0

Views: 370

Answers (1)

Majid
Majid

Reputation: 2890

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:

Upvotes: 1

Related Questions