【问题标题】:accessing realtime DB from firebase functions从 firebase 函数访问实时数据库
【发布时间】:2019-02-16 13:42:33
【问题描述】:

我们正在为我们的移动应用使用 firebase 函数和 firebase 实时数据库。当有人下订单时,我们会发送电子邮件,该订单使用如下 firebase 数据库触发器实现:

exports.on_order_received = functions.database.ref("/orders/{id}")
    .onCreate((change, context) => {
        console.log("start of on_order_received")   
...

上面的触发器对我们来说很好用。现在,我们有一些要求,我们在图片中没有 DB 触发器。这是一个像下面这样的http请求

exports.daily_sales_report = functions.https.onRequest((req, res) => {
    //query data from firebase

问题是我们如何在这里访问实时数据库对象?或者换句话说,我如何访问 /orders 节点?我试过如下

exports.daily_sales_report = functions.https.onRequest((req, res) => {
    //query data from firebase
    var ref = functions.database.ref('orders')
    ref.orderByValue().limitToLast(3).on("value", function(snapshot) {
        snapshot.forEach(function(data) {
          console.log("The " + data.key + " dinosaur's score is " + data.val());
        });
    })

但这不起作用。我收到错误“orderByValue() 不是函数”

【问题讨论】:

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


    【解决方案1】:

    您应该使用Firebase Admin SDK。它具有读取和写入数据库的能力。实际上,当您编写数据库触发器时,它为您提供的 refs 实际上来自 Admin SDK,因此它是相同的 API。使用 HTTP 类型函数时只需要自己初始化即可:

    // at the top of the file:
    const admin = require('firebase-admin');
    admin.initializeApp();
    
    // in your function:
    const root = admin.database().ref();
    // root is now a Reference to the root of your database.
    

    【讨论】:

    • 我有点猜到了,但后来我遇到了这个问题,比如它是如何与数据库触发器一起工作的。很高兴你也回答了这个问题。
    【解决方案2】:

    您必须使用admin 而不是functions 来访问database() 来读取数据。

    (请确保您可以访问 firebase-admin sdk,根据您使用的是 TypeScript 还是 JavaScript,酌情使用 importrequire

    // The Firebase Admin SDK to access the Firebase Realtime Database.    
    import * as admin from 'firebase-admin';
    

    // The Firebase Admin SDK to access the Firebase Realtime Database.
    const admin = require('firebase-admin');
    

    试试这个:

    exports.daily_sales_report = functions.https.onRequest((req, res) => {
        //query data from firebase
        /* Do not use functions */ 
        // var ref = functions.database.ref('orders')
        /* Instead use the admin */
        var ref = admin.database().ref('orders')
        ref.orderByValue().limitToLast(3).on("value", function(snapshot) {
            snapshot.forEach(function(data) {
              console.log("The " + data.key + " dinosaur's score is " + data.val());
            });
        })
    

    orderByValue() 未在 functions.database 中定义 - 但实际上在 admin.database().ref() 中可用

    【讨论】:

      猜你喜欢
      • 2021-06-14
      • 2019-04-13
      • 2021-04-22
      • 2021-04-13
      • 2020-08-13
      • 2022-01-04
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      相关资源
      最近更新 更多