簡體   English   中英

如何在 Firebase 函數中訪問 Firebase 數據庫的快照?

[英]How to access snapshot of Firebase database within Firebase Function?

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

您正在嘗試使用 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
})

firebase-functions與客戶端不同。 根據文檔的ref()函數:

參考:功能

ref(path: string): RefBuilder

選擇要收聽的 Firebase 實時數據庫參考。

要監聽的數據庫路徑。

返回 RefBuilder

RefBuilder將包含您可以調用的數據庫觸發器onCreate()onWrite() 為了能夠使用您的數據庫,您需要使用 admin sdk。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM