반응형
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) {
// ...
}
});
도움이 되길..
집합에 있는 모든 문서의 일부 등록 정보를 업데이트합니다.
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
반응형
'programing' 카테고리의 다른 글
Woocommerce 주문 시 BCC가 관리자에게 이메일을 전송합니다. (0) | 2023.07.04 |
---|---|
주문 후 결과 집합의 첫 번째 행만 어떻게 얻을 수 있습니까? (0) | 2023.07.04 |
유형 스크립트 열거값을 사용하여 새 유형 작성 (0) | 2023.07.04 |
올바른 데이터베이스 선택: MySQL vs.그 외 모든 것 (0) | 2023.07.04 |
VBA Match에서 오류 2042가 표시되는 이유는 무엇입니까? (0) | 2023.07.04 |