【问题标题】:How to read Firebase Database entry in Firebase Cloud Functions' index.js?如何在 Firebase Cloud Functions 的 index.js 中读取 Firebase 数据库条目?
【发布时间】:2017-09-28 18:28:41
【问题描述】:

我正在尝试使用 Firebase Cloud 功能为 iOS 应用创建设备到设备的推送通知。每当在引用'/user-notifications/{notificationRecipientUid}/{challengeId}'的数据库中创建一个新孩子时,我想触发一个事件。这是我的 index.js 代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendWinLoseOrTieNotification = functions.database.ref('/user-notifications/{notificationRecipientUid}/{challengeId}').onWrite(event => {
...
const challengeId = event.params.challengeId;

functions.database.ref('/challenges/' + challengeId).once('value').then(function(snapshot) {
    const challengerUid = snapshot.val().challengerUid;
    ...
});
});

当在该位置的数据库中添加新子项时,我在 Firebase 控制台的函数日志中收到此错误“TypeError: functions.database.ref(...).once is not a function”。所以没有可用的“一次”方法 在 ref 上就像在 web api 中一样:

firebase.database().ref('...').once('value').then(function(snapshot) { ... });

我的问题是:如何读取 index.js 中的现有数据库值?

【问题讨论】:

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


    【解决方案1】:

    好吧,解决方案是像这样使用 admin 而不是 firebase:

    admin.database().ref('...').once('value').then(function(snapshot) {
        ...
    });
    

    【讨论】:

    • 这样做的原因是您将管理 SDK 导入到一个名为 admin: const admin = require('firebase-admin') 的 const 中
    • 我在使用此代码时收到错误 500,但我不知道如何调试.. Webhook 调用失败。错误:500 内部服务器错误
    • @Waza_Be 我不是网络开发人员,但我认为 webhook 用于加载外部包,如 firebase-functions、node mailer 等。您必须将其安装在您的计算机中才能需要此类包,例如在:常量函数=要求('firebase-functions');在这种情况下,您不是部署到您的机器上,而是部署到安装了所有 webhook 的 google 服务器,因此您不会在此处收到此错误。
    • @Waza_Be 如果您还没有这样做,请执行以下操作: npm install firebase-functions@latest --save npm install -g firebase-tools 转到项目目录并运行: firebase login firebase init functions Put在 functions/index.js 中的代码,然后运行: firebase deploy --only 我认为可以的函数。查看firebase.google.com/docs/functions/get-started获取详细指南。
    猜你喜欢
    • 2019-10-03
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多