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

ugmeyewa  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(146)

我已经遵循了文档并在GitHub示例页面阅读了this示例,但我仍然有一个小问题,我没有看到它。
为了说明我在做什么,我将在下面解释。
我有这个数据库结构(对不起的图像和一些西班牙语的代码)

我的目标是每当一个新的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无论它的变化(这是工作的权利)
1.获取clientes下的每个用户,获取notificar号(这是我卡住的地方)
1.比较每个数字并发送通知(这也是正确的)

anauzrmj

anauzrmj1#

您正在获取特定节点的所有子节点并检索它们的值。对于你的例子,你可以把它改成这样-

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
    })
  })

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

iovurdzv

iovurdzv2#

您的问题来自这样一个事实,即当您这样做时,userId是未定义的

return databaseRoot.child('/farmacia/clientes/{userID}')...

看看你提到的例子:

exports.sendFollowerNotification = functions.database.ref('/followers/{followedUid}/{followerUid}')
    .onWrite(async (change, context) => {
      .....
      const followedUid = context.params.followedUid;
      .....
      .....
      const getDeviceTokensPromise = admin.database()
.ref(`/users/${followedUid}/notificationTokens`).once('value');

最后一行使用了Template Literals,这是ES6的一个“新”特性,请参阅https://developers.google.com/web/updates/2015/01/ES6-Template-Stringshttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals,并注意使用了反引号(``)而不是单引号。
然后,注意followedUid常量是如何从{followedUid}占位符计算出来的,该占位符位于触发函数的路径中(使用context.params.followedUid;)。
在你的例子中,路径中没有userID占位符,也没有使用context.params来定义函数中的userId,所以最后'/farmacia/clientes/{userID}'不会返回你期望的路径。

相关问题