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

查看:86
本文介绍了如何在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天全站免登陆