是否可以仅通过一个请求在 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 多个写入操作 https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes
希望能帮助到你..
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)