【问题标题】:How to fetch firebase database data in cloud function?如何在云功能中获取 Firebase 数据库数据?
【发布时间】:2018-08-20 02:56:06
【问题描述】:

我正在使用 firebase 数据库来存储我的 iOS 应用数据。

我正在此应用中保存用户跟踪数据,该应用运行良好。

我必须使用保存在“IOS”字段中的推送令牌向用户 (userID = 57411405) 发送推送通知。

我正在使用的这个云功能:

此云功能运行良好。我能够跟踪保存新跟踪数据的事件。这是此云功能的日志:

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

// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions

exports.databasechanges = functions.database.ref('/users/{id}/LocationTracking').onWrite(event =>{

var eventSnapshot = event.data

console.log('UserId - ', event.params.id);

const userID = event.params.id
const root = event.data.ref.root

admin.database().ref('users/{id}/NotificationToken').on('value').then((snapshot) => {

  var token = snapshot.val().IOS;

  console.log('token',token)

  return snapshot.val();
}).catch(error => {
  console.error(error);
  res.error(500);
});

return eventSnapshot.val()

});

但在云功能控制台上我收到此错误:

现在,我无法弄清楚如何访问此推送令牌(IOS)并使用云功能发送推送通知。

【问题讨论】:

  • 请不要显示代码图像。最好将问题中的代码复制到代码块中,这样更易​​于阅读和搜索。
  • @DougStevenson 我用更多细节编辑了我的问题。

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


【解决方案1】:

要获得“IOS”字段,试试这个:

//inside the trigger function
admin.database().ref('/users/'+event.params.id+'/NotificationToken/IOS').once('v‌​alue').then((snapshot) => { 
var token=snapshot.val().IOS;

 });

【讨论】:

  • 我收到此错误:24:1 错误预期 catch() 或返回 promise/catch-or-return
  • 云功能已成功部署,但云功能控制台出现错误。我编辑了我的问题,请看一下。
  • @ajeetsharma 使用 once() 而不是 on() 并获取一次值
  • 它不起作用:(。在控制台中出现此错误:TypeError: Cannot read property 'IOS' of null at admin.database.ref.once.then (/user_code/index.js:34: 29) 在 process._tickDomainCallback (internal/process/next_tick.js:135:7)
猜你喜欢
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-26
  • 2019-05-07
  • 1970-01-01
  • 2018-02-01
相关资源
最近更新 更多