首页 > 解决方案 > 尝试从 Node.js Firebase 函数中读取 Firebase 数据库时无法确定 Firebase 数据库 URL

问题描述

我正在使用 Flutter 构建一个访问 Firebase 数据库的应用程序。从 Flutter 方面来说一切都很好......但我是 Node.js 和 Cloud Functions 的新手。我正在尝试创建一个 Node.js 函数来对一个 Firebase 数据库节点上的记录的删除事件做出反应,然后从其他两个 Firebase 数据库节点中删除记录并从 Firestore 中删除图像文件。

我正在通过functions.database.onDelete调用对触发事件做出反应,没问题,但在尝试读取 admin.database 以获取快照时遇到了下一个障碍。

我创建了一个虚拟函数,用于.onUpdate获取触发事件(不想像使用时那样重新创建数据.onDelete),然后尝试读取我的 Firebase 数据库以访问不同的节点。触发事件被很好地拾取,但我似乎没有数据库引用 URL 来进行读取......但它是同一个数据库。来自调用的控制台日志上的输出process.env.FIREBASE_CONFIG显示 URL 存在。

包含的功能代码还具有注释以显示我在控制台日志中获得的各种输出。

我为此发疯了.....请任何人都可以告诉我哪里出错了。过去两天一直在搜索 Google、Stackoverflow、Firebase 文档 :-(


const admin = require("firebase-admin"); // Import Admin SDK
const functions = require("firebase-functions"); // Import Cloud Functions

admin.initializeApp({
  credential: admin.credential.cert(
    require("./user-guy-firebase-adminsdk.json")
  )
});

exports.testDeleteFunction = functions.database
  .ref("/user-guys/{userGuyId}")
  // Using .onUpdate as I don't want to keep restoring my data if I use .onDelete
  .onUpdate((snapshot, context) => {

    const userData = snapshot.after.val();
    const userId = userData.userId;

    console.log('userId: ' + userId);         // Gives correct console log output: userId: wajzviEcUvPZEcMUbbkPzcw64MB2

    console.log(process.env.FIREBASE_CONFIG);
    // Gives correct console log output:
    // {"projectId":"user-guy","databaseURL":"https://user-guy.firebaseio.com","storageBucket":"user-guy.appspot.com","cloudResourceLocation":"us-central"}


    // I have tried each of the four following calls and received the console log message as indicated after each.
    // 
    // var root = admin.database.ref();       // Console Log Message: TypeError: admin.database.ref is not a function
    // var root = admin.database().ref();     // Console Log Message: Error: Can't determine Firebase Database URL.
    // var root = admin.database.ref;         // Fails at line 31 below with the message indicated.
    // var root = admin.database().ref;       // Console Log Message: Error: Can't determine Firebase Database URL.

    console.log(root.toString);               // Console Log Message: TypeError: Cannot read property 'toString' of undefined.

    // This is intended to read a chat thread for two users but processing never gets here.
    var database = root.child('chats').child('0cSLt3Sa0FS26QIvOLbin6MFsL43GUPYmmAg9UUlRLnW97jpMCAkEHE3');

    database
      .once("value")
      .then(snapshot => {
        console.log(snapshot.val());
      }, function (errorObject) {
        console.log("The read failed: " + errorObject.code);
      });
    return null; // Will do stuff here once working.
  });

代码注释中显示的错误消息。

标签: node.jsfirebasefirebase-realtime-databasegoogle-cloud-functionsfirebase-admin

解决方案


如果要使用 FIREBASE_CONFIG 中的配置,则应不带参数初始化 Admin SDK:

admin.initializeApp();

这将为您的项目使用默认服务帐户,该帐户应具有对数据库的完全读写访问权限。


推荐阅读