繁体   English   中英

如何批量更新arrays?

[英]How to batch update arrays?

所以我正在创建一个考勤应用程序,其中有一个名为与会者的列表,其中包含所有参加讲座的学生的列表。

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

而学生数据model如下

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

每个学生的文档名称是他们的用户 ID
如何通过batch() function 更新每个学生的列表?

我假设您已经有一个包含user-id的与会者列表,正如您提到的那样, userId将是 Firestore 中的documentId

因此,您可以循环并直接update您的文档,然后使用commit来应用您的更改。

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');
  }
}

一些注意事项:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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