javascript - Firebase 函数 - 无法读取用户 ID 内的属性

标签 javascript firebase google-cloud-platform google-cloud-functions

我已按照文档阅读并阅读 this GitHub 示例页面上的示例,但我仍然有一个小问题,我没有看到它。

为了将我想要做的事情放在上下文中,我将在下面进行解释。

我有这个数据库结构(抱歉图像和代码上有一些西类牙语)

enter image description here

我的目标是每当新的 turno 写入数据库时​​触发一个事件,所以假设它将是 76,77,78.. 等等上。

现在,我的客户将 notificar 号码发送到 clientes - userID 下,并生成 device_token

现在,我正在尝试获取与 turno 内的值匹配的每个客户端的值,因此,如果该值匹配,我将仅向 clientes 发送推送通知 匹配相同的号码。

但是我的 Firebase 函数控制台遇到问题

TypeError: Cannot read property 'notificar' of null at databaseRoot.child.once.then (/user_code/index.js:23:51) at process._tickDomainCallback (internal/process/next_tick.js:135:7)

这是我为触发此行为而编写的代码

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

//Uso el trigger onWrite, para ver cuando hay un nuevo turno, se ejecute toda esta funcion.
exports.sendClientesNotification = functions.database.ref('/farmacia/turno')
    .onWrite((snapshot, context) => {

        //Obtenemos el turno que va cambindo y lo guardamos en nuevoTurno
        const nuevoTurno = snapshot.after.val();
        console.log('Turno nuevo: '+nuevoTurno);


        const databaseRoot = snapshot.before.ref.root;
        return databaseRoot.child('/farmacia/clientes/{userID}').once('value').then((snapshot) =>{

    //Obtengo los valores de la referencia con el wildcard
            const getNumeroNotificar = snapshot.child('notificar').val();
            const getDeviceToken  = snapshot.child('device_token').val();
            console.log('Token: '+deviceToken+" Notificar: "+numeroNotificar);

           //Envio los valores a la promesa para luego mandar la notificacion
        return Promise.all([getNumeroNotificar, getDeviceToken]).then(results => {

            //Guardamos 
            const devicetoken = results[0];
            const numeroturnocliente = results[1];

            console.log('Nueva notificacion para '+devicetoken+' para el turno '+numeroturnocliente);

            if(numeroturnocliente === nuevoTurno){
             const payload = {
                    "data": {
                        "title": "Su turno ah llegado",
                        "body": "el turno "+numeroturnocliente+" es el siguiente a ser atendido.",
                        "icon": "ic_launcher",
                        "sound": "default",
                        "click_action": "delete_token"
              }
        };
                return admin.messaging().sendToDevice(devicetoken,payload);
         }else{
             return 0;
    }



  });

        });


    });

我知道错误就在这里

const getNumeroNotificar = snapshot.child('notificar').val();

并且也将位于其下方的行中,但我无法弄清楚为什么不获取该位置的值。我已经更改了引用并查找了代码几次。由于我正在学习 javascript,有时我经常会遇到这种错误。

简单来说,我正在尝试

  1. 在任何改变的地方获取turno(这是正确的)
  2. 获取 clientes 下的每个用户,获取通知号码(这是 我被困住的地方)
  3. 比较每个数字并发送通知(此操作正常 也对)

最佳答案

您正在获取特定节点的所有子节点并检索它们的值。因此,对于您的示例,您可以将其更改为这样的 -

  databaseRoot.child('/farmacia/clientes').once('value').then(snapshot => {
    const clientes = {}
    snapshot.forEach(data => {
      const key = data.key
      const value = data.val()
      //Do what you need, example-
      clientes[key] = value
    })
  })

此外,getNumeroNotificar getDeviceToken 不是函数,因此您不需要在 Promise.all() 中运行它们。 val()是同步操作。

关于javascript - Firebase 函数 - 无法读取用户 ID 内的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53054804/

相关文章:

javascript - JSON.stringify 没有对整个对象进行字符串化

java - 使用 Firebase 将多行写入 Java 中的 CSV 文件

google-cloud-platform - 如何从前端移动客户端发布到 Google Pub/Sub?

firebase - 如何使用 Cloud Functions 和 Cloud FIrestore 维护状态

firebase - 安全 API 身份验证和 $ 变量不相等

go - 每个HTTP请求是否应该有一个新的datastore.Client?

google-cloud-platform - 有没有办法通过存储在 Google Cloud Storage 中的文本文档进行 grep?

JavaScript 函数仅匹配 Google URL

javascript - 在onclick中获取动态添加元素的id

javascript - JavaScript 如何处理嵌套函数中的参数?