56

是否可以仅通过一个请求将多个文档存储在 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)
}
4

4 回答 4

88

来自 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 多个写入操作

希望能帮助到你..

于 2017-10-07T11:55:44.787 回答
8

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

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))
}
于 2018-08-22T11:51:32.677 回答
2
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  );
    }
于 2019-08-18T17:01:54.030 回答
1

如果您需要使用 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 db 生成 id 时,这可能很有用。

于 2020-05-18T06:43:30.560 回答