【问题标题】:How to access snapshot of Firebase database within Firebase Function?如何在 Firebase Function 中访问 Firebase 数据库的快照?
【发布时间】:2020-06-21 23:59:21
【问题描述】:

每小时,我希望我的 firebase 函数查看我的数据库,读取一个值,从这个旧值计算一个新值,然后在数据库中更新它。我无法访问数据的快照。具体来说,

exports.scheduledFunction = functions.pubsub.schedule('every 1 hour').onRun((context) => {
  const ref = functions.database.ref('/users/test_user/commutes');
  ref.once('value',function(snapshot) {
   // do new calculation here

  }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
  });
  return null;
});

我收到一个:functions: TypeError: ref.once is not a function 错误。

如何访问我的 firebase 实时数据库中的值并通过 Firebase 函数更新它?

【问题讨论】:

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


    【解决方案1】:

    您正在尝试使用 firebase-functions SDK 来查询数据库。它不能那样做。您必须使用Firebase Admin SDK 进行查询。

    你需要像这样开始(不完整,但你应该能够看到你需要做什么)。在全局范围内导入和初始化:

    const admin = require('firebase-admin')
    admin.initializeApp()
    

    然后在你的函数中使用它。确保正确使用 Promise。

    const ref = admin.database().ref('...')
    return ref.once('value').then(snapshot => {
        // work with the snapshot here, and return another promise
        // that resolves after all your updates are complete
    })
    

    【讨论】:

      【解决方案2】:

      firebase-functions 与客户端不同。根据文档,ref() 函数:

      参考:函数

      ref(path: string): RefBuilder

      选择要收听的 Firebase 实时数据库参考。

      要监听的数据库路径。

      返回 RefBuilder

      RefBuilder 将包含您可以调用的数据库触发器 onCreate()onWrite()。为了能够使用您的数据库,您需要使用 admin sdk。

      https://firebase.google.com/docs/reference/functions/providers_database_.refbuilder

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-30
        • 2017-07-27
        • 2016-04-09
        • 2019-01-07
        • 2020-06-11
        • 2017-01-30
        • 1970-01-01
        相关资源
        最近更新 更多