如何阅读Firebase云功能的index.js中的Firebase数据库条目?

nae*_*aid 5 javascript push-notification firebase firebase-realtime-database google-cloud-functions

我正在尝试使用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;
    ...
});
});
Run Code Online (Sandbox Code Playgroud)

当在该位置的数据库中添加新子项时,我在Firebase控制台的函数日志中收到此错误,"TypeError:functions.database.ref(...).曾经不是函数".因此,在web api中,ref上没有"一次"方法可用:

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

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

nae*_*aid 5

好吧,解决方案是使用admin代替firebase,如下所示:

admin.database().ref('...').once('value').then(function(snapshot) {
    ...
});
Run Code Online (Sandbox Code Playgroud)

  • 原因是将admin SDK导入名为admin的const中:const admin = require('firebase-admin')` (2认同)