使用dart和Firestore在一次交易中更新多个文档

时间:2019-01-14 21:14:27

标签: firebase flutter google-cloud-firestore

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

  1. 将属性为“ position:1”的新项目添加到文档集合中
  2. 以> 1 x 1(++)的位置递增此集合中所有其他文档的“ position”属性

单个文档如下:

{
    "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());

});

}

1 个答案:

答案 0 :(得分:0)

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

  1. 运行查询以确定所有受影响的文档
  2. 开始交易
  3. 创建新文档
  4. 对受影响的文档以及每个文档进行遍历:

    1. 从交易中读取文档
    2. 更新文档数据
    3. 通过交易回写文件

尝试一下,如果遇到麻烦,请发回code that reproduces where you got stuck

相关问题