node.js - 我无法读取 Firebase Functions 上的数据

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

我使用 firebase 函数来触发推送通知。

我可以发送通知,但在触发器启动时无法读取某些数据。

我尝试了常用的 Firebase 数据库功能,但它们不起作用。

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

let fcm = ''
exports.sendNewMessageNotification = functions.database.ref('/xxx/userInformations/{uid}/')
    .onWrite((change:any) => {
    // console.log(change.before)
      const payload = {
          notification: {
              title: 'Kahve Falı',
              body: 'Falın geldi!',
      }
    }
    admin.database().ref('/xxx/userInformations/{uid}/fortunes')
    .once('value')
    .then((snapshot:any) => {
      console.log('snapshot.val()')//I want to get that snaphot.val()

      });
      fcm = change.before._data.fcm;
      return admin.messaging().sendToDevice(fcm, payload);
    });

它不会读取该快照。它以不同的方式返回 null 或 undefined。 我不能那样做这条线; .then((快照) => {

如果我不输入 :any ,则会在 VS Code 上出现错误。

最佳答案

您似乎弄错了代码的两部分。

<小时/>

首先你有:

exports.sendNewMessageNotification = functions.database.ref('/xxx/userInformations/${uid}/')

这声明了一个云函数。当您使用 Firebase 部署此代码时,它会识别此 Cloud Function 并将字符串文字 '/xxx/userInformations/${uid}/' 解释为此代码需要触发的路径。它将路径中 /xxx/userInformations 之后的值放入名为 uid 的参数中。

<小时/>

接下来你有:

admin.database().ref('/xxx/userInformations/${uid}/fortunes')

这是常规 JavaScript 代码,在这种情况下,'/xxx/userInformations/${uid}/fortunes' 只是发送到 Firebase 客户端的字符串。由于路径中不允许使用 $,Firebase 客户端会引发错误。

您可能希望路径包含 uid 参数的,您可以使用以下方法:

admin.database().ref(`/xxx/userInformations/${context.params.uid}/fortunes`)

所以变化:

  1. 使用反引号标记字符串,以便将其解释为 ES6 Template Literal .
  2. 在其中使用 ${context.params.uid} 来获取用于触发代码的 uid 值。

这要求您在 Cloud Function 声明中定义上下文,例如:

.onWrite((change:any, context: any) => {

关于node.js - 我无法读取 Firebase Functions 上的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57746246/

相关文章:

javascript - 云功能中的 firebase 分布式计数器扩展

javascript - 每天在 5 :00 AM using firebase javascript 清除 firebase 数据库值

ios - 如何将数据添加到firebase数据库中的特定使用引用?

node.js - 获取nodeJS中所有用户的流列表

node.js - 来自 SFTP 连接的 Node 异步 ReadStream

javascript - Sequelize : Foreign key declared, 但没有出现在表中

android - 启用以查看 firebase 错误控制台日志

javascript - 从 Node + Express API 中提取使用 res.json 发送的信息

android - Android错误:Firebase数据库组件不存在

android - FirebaseListAdapter - 查询