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

标签 android firebase google-cloud-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)
}

最佳答案

来自 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/

相关文章:

firebase - 使用 firebase 访问谷歌云数据存储数据

ios - FIRInstallations使Firebase iOS SDK崩溃validateAppOptions:appName

node.js - 更新 Firestore 文档需要超过 3 分钟

android - 使用倾斜传感器的 Arduino 程序中的正确功能顺序

android - 从 Firebase 注销召回使用电子邮件和密码登录

android - 如何获取 Android 11 中已安装应用程序的列表

ios - 与 Firestore 监听器分离

javascript - 云HTTPS函数: returning a Promise which is inside a Promisee

android - Room 生成的类的发布构建失败 : javax. 注释不存在

java - RecyclerView 的 SearchView 不起作用