Как создать/обновить сразу несколько документов в 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)
}
Ответы
Ответ 1
Из документации 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
Надеюсь, что это поможет.
Ответ 2
Обновите некоторые свойства всех документов в коллекции:
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))
}
Ответ 3
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 );
}