【问题标题】:Firebase: Transaction read and update multiple documentsFirebase:事务读取和更新多个文档
【发布时间】:2018-04-29 14:24:28
【问题描述】:

使用此代码,我可以读取和更新事务中的单个文档。

// Update likes in post
var docRef = admin
  .firestore()
  .collection("posts")
  .doc(doc_id);

let post = await admin.firestore().runTransaction(t => t.get(docRef));
if (!post.exists) {
  console.log("post not exist")
}
postData = { ...post.data(), id: post.id };
let likes = postData.likes || 0;
var newLikes = likes + 1;
await post.ref.update({ likes: newLikes });

问题: 但我需要阅读和更新 多个 文档,并且每个文档都根据其内容进行更新。例如,我想像在我的代码中一样更新帖子集合中的点赞数,但还要更新我的个人资料文档中的总点赞数。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    要更新事务中的多个文档,请多次调用t.update()

    let promise = await admin.firestore().runTransaction(transaction => {
      var post = transaction.get(docRef);
      var anotherPost = transaction.get(anotherDocRef);
    
      if (post.exists && anotherPost.exists) {
        var newLikes = (post.data().likes || 0) + 1;
        await transaction.update(docRef, { likes: newLikes });
        newLikes = (anotherPost.data().likes || 0) + 1;
        await transaction.update(anotherdocRef, { likes: newLikes });
      }
    })
    

    https://firebase.google.com/docs/firestore/manage-data/transactions#transactions

    【讨论】:

    • 但是这里我们只从一个文档中读取数据。我需要根据他们的点赞数而不是 docRef 点赞数来更新 anotherdocRef。
    • 您可以在事务中对多个文档引用调用transaction.get(...)
    • 我从您的代码中复制了它。现在更新以消除该问题的可能原因。但请注意,我试图表明您可以在事务处理程序中调用 transaction.get(...) multiple 来解决您的问题。
    • 发现错误:需要在 "transaction =>" 之前添加 async 并将 await 放在 post 和 anotherPost 声明上
    • @FrankvanPuffelen 是否像批量更新一样,firestore 事务更新全部失败或成功?
    猜你喜欢
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    相关资源
    最近更新 更多