【问题标题】:can't retreive data from firebase database ( cloud functions )无法从 firebase 数据库中检索数据(云功能)
【发布时间】:2018-02-01 11:47:48
【问题描述】:

我正在使用 firebase 云函数来监听数据库值事件,这是我的代码

    var functions = require('firebase-functions');
var firebase = require('firebase-admin');

var serviceAccount = require("./serviceAccountKey.json");

firebase.initializeApp({
    credential : firebase.credential.cert(serviceAccount),
    databaseURL: "https://*******.firebaseio.com"
});

exports.notifications = functions.database.ref('/chat/{senderID}/{destinationID}/messages/{pushID}')
    .onWrite(event => {        
        var eventSnapshot = event.data;        
        var sender = eventSnapshot.child('sender').val();
        var message = eventSnapshot.child('message').val();
        var destination = eventSnapshot.child('destination').val();        
        if (event.params.senderID === sender) 
            sendMessage(message,sender,destination);    
    }
);

function sendMessage(message, sender, destination) {

    var senderUser = firebase.database().ref('users/'+sender+'/name'); 
    var tokenUser = firebase.database().ref('fcm/'+destination+'/token');
        tokenUser.once('value').then(function(tokenSnapshot) {
            var token = tokenSnapshot.val(); 
                        console.log(token);                        

    }, function (errorObject) {
  console.log("The read failed: " + errorObject.code);
});     
}

onWrite函数正常执行,但tokenUser.once()没有执行。

【问题讨论】:

  • 这是真的吗? event.params.senderID === sender 。将一些日志语句与它们的输出一起放在那里,这样我们至少可以知道你运行它时发生了什么。
  • sendMessage 函数正在执行,我用日志对其进行了测试,所以问题出在数据检索函数上
  • 您的 DB 中有 fcm/'+destination+'/token 的内容吗?
  • 是的,这是一条正确的路径
  • 我有,但如果我没记错的话,我遇到了一个空值只输出换行符(而不是未定义或空值)的问题。因此,您可能需要仔细检查以下情况是否没有发生:console.log('my token is ', token);

标签: node.js firebase firebase-realtime-database google-cloud-functions firebase-admin


【解决方案1】:

也许如果你尝试使用tokenUser.once('value') 并且不传递函数,直接获取tokenSnapshot;像这样:

tokenUser.once('value').then(tokenSnapshot => {
        var token = tokenSnapshot.val(); 
        console.log(token);                        

});     

如果你使用带有回调的tokenUser.once(),你可以传递函数;像这样:

tokenUser.once('value', function(tokenSnapshot) {
        var token = tokenSnapshot.val(); 
                    console.log(token);                        

}, function (errorObject) {
  console.log("The read failed: " + errorObject.code);
});   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 2021-09-07
    • 2018-09-04
    • 2018-11-10
    相关资源
    最近更新 更多