是否可以仅使用一个请求在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)
}
答案 0 :(得分:45)
来自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
希望有所帮助......
答案 1 :(得分:3)
更新集合中所有文档的某些属性:
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))
}
答案 2 :(得分: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数据库生成ID时,这可能很有用。
答案 3 :(得分:0)
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 );
}