如何在 Firestore 中一次 create/update 多个文档

How to create/update multiple documents at once in Firestore

是否可以通过一个请求在 Firestore 中存储多个文档? 使用此循环是可能的,但这会导致列表中的每个项目都进行一次保存操作。

for (counter in counters) {
    val counterDocRef = FirebaseFirestore.getInstance()
            .document("users/${auth.currentUser!!.uid}/lists/${listId}/counters/${counter.id}")
    val counterData = mapOf(
            "name" to counter.name,
            "score" to counter.score,
    )
    counterDocRef.set(counterData)
}

来自 Firebase 文档:

您还可以使用 set()、update() 或 delete() 方法的任意组合将多个操作作为单个批处理执行。您可以跨多个文档批量写入,并且批量中的所有操作自动完成。

// Get a new write batch
WriteBatch batch = db.batch();

// Set the value of 'NYC'
DocumentReference nycRef = db.collection("cities").document("NYC");
batch.set(nycRef, new City());

// Update the population of 'SF'
DocumentReference sfRef = db.collection("cities").document("SF");
batch.update(sfRef, "population", 1000000L);

// Delete the city 'LA'
DocumentReference laRef = db.collection("cities").document("LA");
batch.delete(laRef);

// Commit the batch
batch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        // ...
    }
});

Firestore multiple write operations

希望对您有所帮助..

更新集合中所有文档的一些属性:

resetScore(): Promise<void> {
  return this.usersCollectionRef.ref.get().then(resp => {
    console.log(resp.docs)
    let batch = this.afs.firestore.batch();

    resp.docs.forEach(userDocRef => {
      batch.update(userDocRef.ref, {'score': 0, 'leadsWithSalesWin': 0, 'leadsReported': 0});
    })
    batch.commit().catch(err => console.error(err));
  }).catch(error => console.error(error))
}
void createServiceGroups() {
        List<String> serviceGroups = [];

        serviceGroups.addAll([
          'Select your Service Group',
          'Cleaning, Laundry & Maid Services',
          'Movers / Relocators',
          'Electronics & Gadget',
          'Home Improvement & Maintenance',
          'Beauty, Wellness & Nutrition',
          'Weddings',
          'Food & Beverage',
          'Style & Apparel',
          'Events & Entertainment',
          'Photographer & Videographers',
          'Health & Fitness',
          'Car Repairs & Maintenance',
          'Professional & Business Services',
          'Language Lessons',
          'Professional & Hobby Lessons',
          'Academic Lessons',
        ]);
        Firestore db = Firestore.instance;
        // DocumentReference ref = db
        //     .collection("service_groups")
        //     .document(Random().nextInt(10000).toString());

        // print(ref.documentID);

        // Get a new write batch

        for (var serviceGroup in serviceGroups) {
          createDocument(db, "name", serviceGroup);
        }

        print("length ${serviceGroups.length}");
      }

      createDocument(Firestore db, String k, String v) {
        WriteBatch batch = db.batch();
        batch.setData(db.collection("service_groups").document(), {k: v});
        batch.commit();
      }

   createDocument(Firestore db, String k, String v) {
            WriteBatch batch = db.batch();
            batch.setData(db.collection("service_groups").document(), {k: v});
            batch.commit();
          }

这可能对您有帮助:

 for (var serviceGroup in serviceGroups) {
      createDocument(db,  "name", serviceGroup  );
    }

如果您需要使用add()而不是set,请按照下面的代码,

public void createMany(List<T> datas) throws CustomException {
    Firestore firestore = connection.firestore();
    CollectionReference colRef = firestore.collection("groups");

    WriteBatch batch = firestore.batch();
    for (T data : datas) {
        batch.create(colRef.document(), data);
    }

    ApiFuture<List<WriteResult>> futureList = batch.commit();
    try {
        for (WriteResult result : futureList.get()) {
            logger.debug("Batch output: {}", result.getUpdateTime());
        }
    } catch (InterruptedException | ExecutionException e) {
        throw new CustomException(500, e.getMessage());
    }
}

当您需要从 firestore 数据库生成 id 时,这可能会有用。