Firebase函数无法读取未定义的属性“val”

时间:2018-05-20 23:13:22

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

我是Firebase中的新功能,已经阅读了官方文档中的一些更改,但是当我正在做一个通知系统时,当我尝试获取我的令牌ID时,它会向我发出此错误。

我的代码

     'use strict'

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


/*
 * 'OnWrite' works as 'addValueEventListener' for android. It will fire the function
 * everytime there is some item added, removed or changed from the provided 'database.ref'
 * 'sendNotification' is the name of the function, which can be changed according to
 * your requirement
 */

exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {


  /*
   * You can store values as variables from the 'database.ref'
   * Just like here, I've done for 'user_id' and 'notification'
   */

  const user_id = context.params.user_id;
  const notification_id = context.params.notification_id;

  console.log('Tenemos una notificacion para mandar a : ', context.params.user_id);

   if(!context.data.val()){

    return console.log('Una notificacion se elimino de la base de datos : ', notification_id);

  }

  const deviceToken = admin.database().ref(`/users/${user_id}/device_token`).once('value');

  return deviceToken.then(result => {

    const token_id = result.val();

      /*
       * We are creating a 'payload' to create a notification to be sent.
       */

    const payload = {
        notification: {
          title : "Tienes un nuevo seguidor !",
          body: "Tu nuevo seguidor es .... ",
          icon: "default"
        }

      };

       /*
       * Then using admin.messaging() we are sending the payload notification to the token_id of
       * the device we retreived.
       */

      return admin.messaging().sendToDevice(token_id, payload).then(response => {

        return console.log('This was the notification Feature');

      });

  });



  });

错误

  

无法读取undefined的属性'val'       at exports.sendNotification.functions.database.ref.onWrite(/user_code/index.js:28:20)       在对象。 (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)       在下一个(本地)       at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71       在__awaiter(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)       在cloudFunction(/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)       在/var/tmp/worker/worker.js:716:24       at process._tickDomainCallback(internal / process / next_tick.js:135:7)

1 个答案:

答案 0 :(得分:4)

要测试数据是否已删除,请将if语句更改为:

{{1}}

the documentation中描述。