gpt4 book ai didi

firebase - 使用 dart 和 Firestore 在单个事务中更新多个文档

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

我正在尝试创建一个 保存交易使用 Flutter/Dart 和 Firestore 执行以下操作:

  • 将属性为“位置:1”的新项目添加到文档集合
  • 将此集合中所有其他文档的“位置”属性增加一个位置 > 1 乘以 1 (++)

  • 单个文档如下所示:
    {
    "title": "Some title",
    "position": 1
    }

    在文档( https://firebase.google.com/docs/firestore/manage-data/transactions )中,我找到了有关如何在单个文档上进行保存事务的说明,但没有找到有关如何创建我需要在集合中保存插入和更新的“两步原子事务”的说明。

    也许有人对我有暗示?

    更新:
    感谢您的投入弗兰克。这是一个代码片段,希望能解释我想要实现的目标:
    @override
    Future addCatalogItem(CatalogItem catalogItem) {

    return firestore.runTransaction((Transaction transaction) async {

    // Update position (++) of existing catalogItems
    await firestore
    .collection(path)
    .where("catalogId", isEqualTo: catalogItem.catalogId)
    .snapshots()
    .forEach((snapshot) {
    snapshot.documents.forEach((document) {
    // document.reference.updateData({"position": document.data["position"]});
    transaction.update(document.reference, {"position": document.data["position"] + 1});
    });
    });

    // Add the new catalogItem at position 1
    await firestore
    .collection(path)
    .document(catalogItem.id)
    .setData(catalogItem.toJson());

    });

    }

    最佳答案

    事务不能包含查询。因此,您需要首先运行查询以查找匹配的文档,然后获取并更新事务中的每个文档。除此之外,它应该相当简单。

  • 运行查询以确定所有受影响的文档
  • 开始交易
  • 创建新文档
  • 遍历受影响的文档并为每个:
  • 从交易中读取文档
  • 更新文档数据
  • 通过事务写回文档

  • 试一试,如果卡住了,请回帖 code that reproduces where you got stuck .

    关于firebase - 使用 dart 和 Firestore 在单个事务中更新多个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54189298/

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