【问题标题】:Can I read from a query matching multiple documents Firestore Transaction in Flutter我可以从匹配多个文档的查询中读取 Flutter 中的 Firestore 事务吗
【发布时间】:2020-11-05 15:05:42
【问题描述】:

我正在尝试从查询中读取,而不是从事务中的单个文档中读取。
我的写入取决于集合中当前数据的结果。但我似乎明白,至少对于移动和网络客户端,您不能从查询中读取,只能从单个文档读取中读取。

如果是这样,我不知道要提前阅读哪些文件,我该如何实现?

具体来说,我指的是this video from the Firebase team,时间是 9:38

【问题讨论】:

    标签: flutter google-cloud-firestore


    【解决方案1】:

    确实,您无法从事务中的查询中读取文档,只能读取单个文档。

    因此,您必须使用您的条件运行查询以确定文档 ID,然后使用单个更新或一个或多个批量写入而不是事务来更新文档,如果您需要这些写入是原子的。

    这是一个代表我的意思的 sn-p(在 Javascript 中,不是 Flutter,但足以作为一个实际示例):

    var db = firebase.firestore();
    
    const newDocumentBody = {
        message: 'hello world'
    }
    
    db.collection('myCollection').where('message', '==', 'hello').get().then(response => {
        let batch = db.batch();
        response.docs.forEach((doc) => {
            const docRef = db.collection('myCollection').doc(doc.id);
            batch.update(docRef, newDocumentBody);
        })
        batch.commit().then(() => {
            console.log('updated all documents inside myCollection');
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-03
      • 2018-10-25
      • 2021-07-25
      • 1970-01-01
      • 2021-05-04
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多