首页 > 解决方案 > 如何在 Firebase Function 中访问 Firebase 数据库的快照?

问题描述

每小时,我希望我的 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 函数更新它?

标签: javascriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


您正在尝试使用 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
})

推荐阅读