gpt4 book ai didi

android - 如何在 Firestore 中一次创建/更新多个文档

转载 作者:行者123 更新时间:2023-12-02 07:06:17 25 4
gpt4 key购买 nike

是否可以仅通过一个请求在 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 multiple write operations

希望有帮助..

关于android - 如何在 Firestore 中一次创建/更新多个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46618601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com