【问题标题】:Firebase function, increment a valueFirebase 函数,增加一个值
【发布时间】:2020-09-01 10:49:03
【问题描述】:

我有一个 firebase 云函数,它应该在创建新文档时增加字段的值。该函数成功执行,我可以在 firebase 日志中看到这一点,但它不会增加字段的值。

exports.onFileAdded = functions.firestore.document("files/{id}").onCreate(async (change, context) => {
    const file = change.data();

    const hub = await getByCollectionAndId('hubs', file.hubId);

    Firebase.firestore().collection('teams').doc(hub.teamId).set({tileCount: Firebase.database.ServerValue.increment(1)}, {merge: true});
});

由于没有错误,并且函数执行成功,我做错了什么?

【问题讨论】:

  • “似乎没有做任何事情”有点棘手。您是否看到该函数是否在 Cloud Functions 日志中被调用?如果不是,那么 Functions 代码在调试中不会有太大用处,因为它没有运行,你会想看看你是如何触发这个代码的——所以你的 Firestore 的写操作应用程序。
  • 抱歉,我已经重新措辞了我的问题

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


【解决方案1】:

问题是:

Firebase.database.ServerValue.increment(1)

您正在使用运算符来增加实时数据库上的值,但您正在 Cloud Firestore 上使用它。虽然这两个数据库都是 Firebase 的一部分,但它们是完全独立的,一个的 API 不适用于另一个。

要解决此问题,请对 Firestore 使用 increment 运算符:

firebase.firestore.FieldValue.increment(1)

也可以在这里查看我的答案:How to increment existing number field in Cloud Firestore

【讨论】:

  • 我将其更改为Firebase.firestore.FieldValue.increment(1),虽然没有错误,但它仍然没有增加数字。
  • Firebase 的大写是不寻常的,但我想您可能会以该名称导入它。我建议为您的set() 调用添加一个完成侦听器,使用then()catch() 如下所示,以查看SDK 认为操作成功还是失败:firebase.google.com/docs/firestore/manage-data/…
  • 我在then()catch()中添加了一些输出,操作成功,then()的输出显示在函数日志中。
  • 请更新您的问题以包含最新的代码及其输出。
猜你喜欢
  • 1970-01-01
  • 2015-05-09
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
  • 2017-06-09
  • 2016-12-28
  • 2013-05-25
  • 2011-04-18
相关资源
最近更新 更多