繁体   English   中英

Firebase function error: Cannot convert undefined or null to object at Function.keys (<anonymous> )</anonymous>

[英]Firebase function error: Cannot convert undefined or null to object at Function.keys (<anonymous>)

问题描述:

我的应用程序的目标是将家庭支出存储在 Firebase 实时数据库中。 我希望,当存储新支出时,会向所有其他设备发送通知。 我尝试向单个设备发送通知并且它工作正常,但是当我尝试获取数组中的所有令牌时,出现错误:TypeError: Cannot convert undefined or null to object at Z86408593C34AF77FDD90DFs932F8。

index.js 的代码

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

exports.androidPushNotification = functions.database
    .ref("{nodo}/spese/{spesaPush}")
    .onCreate(async (snapshot, context) => {
      const original = snapshot.val();

      const getDeviceTokensPromise = admin.database()
          .ref(`/utenti/{tutti}/token`).once('value');

      let tokensSnapshot;
      let tokens;
      tokensSnapshot = await getDeviceTokensPromise;

      // This is the line generating the errors. 
      // If I get only a specific token and 
      // use tokens = tokensSnapshot.val(); anything works fine
      tokens = Object.keys(tokensSnapshot.val());


      const result = original.chi + " ha speso " +
      original.costo + " € per acquistare " +
      original.desc;
      console.log(result);

      const payload = {
        notification: {
          title: 'New spending inserted!',
          body: result, 
        }
      };

      const response = await admin.messaging().sendToDevice(tokens, payload);
      return result;
    });

似乎尚未达到值,但我认为关键字 await 让系统等待所有数据可用。 从日志中我注意到我需要的值是 null 我不明白为什么。 如果我使用这行代码:

      const getDeviceTokensPromise = admin.database()
          .ref(`/utenti/SpecificUser/token`).once('value');
      ....
      //then
      tokens = tokensSnapshot.val();

通知将发送到具有“SpecificUser”名称下令牌的设备

编辑:我提供了我的数据库的图片。 我注意到没有一个字段是 null,所以我不知道为什么我看到这个错误在此处输入图像描述

感谢任何帮助我的人

我有同样的错误,它是由数据库解决的......当我看到我的数据库值不幸的是我存储了未定义的值,所以我的整个结果像你一样出现错误......查看你的整个值和正确存储值的字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM