node.js - Firebase 事务一次更新文档中的多个字段

标签 node.js firebase google-cloud-platform google-cloud-firestore google-cloud-functions

我正在尝试读取 firestore 文档中的单个字段,将该字段增加 1,然后与文档中的其他两个字段一起更新该字段。

Firebase 事务 update() 函数似乎接受只有一个字段和值的 JSON 对象,因为当我向 JSON 添加其他字段时,更新会失败。

这有效:

t.update(referralCodesDocRef, {field1: value1});

这不起作用:

t.update(referralCodesDocRef, {
field1: value1,
field2: value2,
field3: value3
});

这也不起作用:

t.update(referralCodesDocRef, {field1: value1});
t.update(referralCodesDocRef, {field2: value2});
t.update(referralCodesDocRef, {field3: value3});

这是执行事务的函数

function runIncreaseCountTransaction(referralCodesDocRef){
    return db.runTransaction(t => {
      return t.get(referralCodesDocRef)
      .then(doc => {
        console.log(doc);
        let newReferralCount = doc.data().referral_count + 1;
        if(newReferralCount === max_referral_count){
          const current_time_millis = Date.now();
          const end_time_millis = current_time_millis+(180*1000); // ends after 3 mins
          t.update(referralCodesDocRef, {referral_count: newReferralCount});
          t.update(referralCodesDocRef, { timer_start_time: current_time_millis });
          t.update(referralCodesDocRef, { timer_end_time: end_time_millis });
        }
        else{
          t.update(referralCodesDocRef, { referral_count: newReferralCount });
        }
        return Promise.resolve(newReferralCount);
      })
      .then(result => {
        console.log('Success: Update successful: Referral count incremented!!', result);
        return true;
      }).catch(err => {
        console.log('Error: could not update referral count', err);
      });
    });
  }

那么如何通过 Firebase 事务实现多个字段更新?

最佳答案

没有一个答案是正确的(至少对我来说不起作用)。

Kotlin

这是我的实现。非常简单:

val db = Firebase.firestore
                db.collection("Users")
                    .document("Ronaldo")
                    .update("famous", true,
                        "distance", 5)
                    .addOnSuccessListener {...
                    .addOnFailureListener {...

       

所以基本上在第一对之后添加另一个逗号

关于node.js - Firebase 事务一次更新文档中的多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57924683/

相关文章:

javascript - res.write 不起作用,而 console.log 中同样的事情起作用

javascript - sequelize 和 postgres 按距点的距离排序

google-cloud-platform - gcloud 应用程序部署在 Cloud SDK 版本 297.0.0 上崩溃,时区为 "Unable to assign value to attribute ''"

python - 在 Ubuntu 16.04 LTS 中检测与外部云存储同步的目录中的文件更改

python - 将文件从 Google Compute Engine VM 上运行的 docker 镜像复制到 Google Storage 存储桶

javascript - 是否可以在 TypeScript 中使用类型化流?

python - 在同一个 Dockerfile 中使用 Python 和 Node.js 并创建一个我在云中同时使用的镜像

swift - Firebase:如何将数据放入已使用 childbyAutoID 创建的子对象中

ios - 如何通过 firebase 中的嵌套值获取键名?

javascript - 我的代码中的云功能错误或错误 : www. googleapis.com 网络超时。请再试一次