【发布时间】:2018-10-30 14:24:18
【问题描述】:
我是 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');
});
});
});
错误
无法读取未定义的属性“val” 在exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:28:20) 在对象。 (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27) 在下一个(本机) 在 /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 在 process._tickDomainCallback (internal/process/next_tick.js:135:7)
【问题讨论】:
-
可能 context.data 没有定义。您是否尝试将其注销?
-
我认为上下文工作正常,因为用户 ID 的返回日志工作正常
-
另外,如果我从不删除数据,则永远不会执行 if 语句
-
我认为问题可能出在 const token_id 上,因为 Val() 是唯一的问题
-
@LeoFarmer 是正确的。
context没有名为data的属性。
标签: javascript firebase firebase-realtime-database google-cloud-functions