programing

Firestore에서 여러 문서를 한 번에 생성/업데이트하는 방법

telecom 2023. 7. 4. 21:40
반응형

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

도움이 되길..

집합에 있는 모든 문서의 일부 등록 정보를 업데이트합니다.

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

set 대신 add()를 사용해야 하는 경우 아래 코드를 따르십시오.

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를 생성해야 하는 경우 유용할 수 있습니다.

언급URL : https://stackoverflow.com/questions/46618601/how-to-create-update-multiple-documents-at-once-in-firestore

반응형