【问题标题】:Writing 4 returns for one trigger, that each return is to different docRef为一个触发器编写 4 个返回值,每个返回值指向不同的 docRef
【发布时间】:2018-09-17 17:29:34
【问题描述】:

我想写一个firestore函数来创建一个新文档 它将更新几个不同的文档。

例如,通过将新的运动会话文档添加到会话集合来进行统计。 它将更新文档:yearlyStats、quartlyStats、monthlyStats 和 dailyStats。

所以问题是,我如何为一个触发器编写 4 个返回,每个返回都指向不同的 docRef。

我需要用相同的触发器编写 4 个独立的函数吗?或者我可以在一个函数中完成所有操作?

【问题讨论】:

    标签: firebase firebase-realtime-database google-cloud-firestore google-cloud-functions


    【解决方案1】:

    如果您要根据创建的新文档更新统计信息,则最好使用事务。这样,您将确保 2 个并发文档创建不会同时更新统计文档。您可以让事务从新文档中读取值,然后更新多个文档。

    如果您只是想在云函数中同时写入多个文档,请查看使用批量写入。

    这两个选项的文档都可以在这里找到,Transactions and Batched Writes

    请注意,您只能以每秒一次的速度更新单个文档。如果您正在处理大量文档,那么您最好将新文档数据通过管道传输到 Cloud Dataflow(通过 Cloud Function 中的 PubSub),然后将定期更新传递回 Cloud Firestore。如果这是您的用例,那么这个视频将会很有用...Data Pipelines with Firebase and Google Cloud

    使用事务和 getAll 的代码示例

    这需要 Node SDK 0.12.0 或更高版本(Admin SDK >= 5.9.1)

    const firestore = firebase.firestore();
    
    let firstDocRef = firestore.doc('myCollection/document1');
    let secondDocRef = firestore.doc('myCollection/document2');
    
    return firestore.runTransaction(t => {
      return t.getAll(firstDocRef, secondDocRef).then(querySnapshot => {
    
        // Return just the data and map it to firstDoc and secondDoc (personal hack)
        querySnapshot = querySnapshot.map(doc => doc.data());
        let [firstDocData, secondDocData] = querySnapshot;
    
        // Increment the counters
        let firstUpdate = {myCounter: firstDocData.myCounter + 1};
        let secondUpdate = {myCounter: secondDocData.myCounter + 1};
    
        // Write the new data back to Cloud Firestore
        t.update(firstDocRef, firstUpdate);
        t.update(secondDocRef, secondUpdate);
    
      });
    })
    .then(() => {
      console.log('Transaction completed successfully');
    })
    .catch(err => {
      console.error(err);
    });
    

    【讨论】:

    • 使用批处理选项写入文档是一个不错的选择,但由于这些字段是计数器,因此在更新之前,我需要从文档中读取它们。批处理选项是否允许? (阅读几个文档,然后使用批处理更新文档)
    • 您可以使用transaction.getAll在一个事务中读取多个文档。获得所有文件后,只需在事务中根据需要更新文件,然后返回函数 文件中有错误(已报告)。数组应该获取对象 0 和 1,而不是 1 和 2。
    • 我可以在事务中使用 writeBatch 吗?我正在尝试,但它返回给我“函数返回未定义、预期的承诺或值”。如果可能的话,我如何在 writeBatch.commit() 之后关闭这个事务函数;命令??
    • 我在我的答案中添加了一个代码示例。希望这会有所帮助
    • 我刚刚发现我的代码中有一个小错字。如果你已经复制了,请更新
    【解决方案2】:

    您可以通过将四个写入的承诺组合成对Promise.all() 的调用并从您的函数中返回它来做到这一点。

    看看Promise.all() the MDN documentation,或者之前的questions where Promise.all() was used

    【讨论】:

      猜你喜欢
      • 2012-01-27
      • 2021-08-23
      • 2011-04-07
      • 2021-10-21
      • 1970-01-01
      • 2018-04-28
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多