如何在 Firestore 中一次创建/更新多个文档 [英] How to create/update multiple documents at once in Firestore

查看:32
本文介绍了如何在 Firestore 中一次创建/更新多个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以仅通过一个请求在 Firestore 中存储多个文档?使用此循环是可能的,但这会导致列表中的每个项目进行一次保存操作.

Is it possible to store multiple documents in Firestore with only one request? With this loop it's possible but this would cause one save operation per item in the list.

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 文档:

From Firebase documentation :

您还可以使用 set()、update() 或 delete() 方法的任意组合,将多个操作作为单个批处理执行.您可以跨多个文档批量写入,批处理中的所有操作都是原子完成的.

You can also execute multiple operations as a single batch, with any combination of the set(), update(), or delete() methods. You can batch writes across multiple documents, and all operations in the batch complete atomically.

// 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 多次写入操作

希望有帮助..

这篇关于如何在 Firestore 中一次创建/更新多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆