![](/img/trans.png)
[英]TypeError: Cannot read property 'match' of undefined when calling Firebase Cloud Function
[英]“TypeError: Cannot read property 'child' of undefined” when triggering cloud function
我有一個雲函數,每當有新消息寫入與該用戶關聯的數據庫時,它都會向接收器發送通知。 我似乎不斷收到錯誤。
我是雲功能的新手,似乎無法解決這個問題。
看下面的雲功能
exports.sendNotification = functions.database.ref('/messages/{userId}/{messageId}')
.onWrite((snapshot,context) => {
//get the userId of the person receiving the notification because we need to get their token
const receiverId = context.params.userId;
console.log("receiverId: ", receiverId);
//get the user id of the person who sent the message
//const senderId = context.data.child('senderUid').val();
const senderId = snapshot.data.child('senderUid').val();
console.log("senderId: ", senderId);
//get the message
const message = snapshot.data.child('messageBody').val();
console.log("message: ", message);
//get the message id. We'll be sending this in the payload
const messageId = context.params.messageId;
//const messageId = event.params.messageId;
console.log("messageId: ", messageId);
//query the users node and get the name of the user who sent the message
return admin.database().ref("/Renters/" + senderId).once('value').then(snap => {
const senderName = snap.child("houseName").val();
console.log("senderName: ", senderName);
//get the token of the user receiving the message
return admin.database().ref("/users/" + receiverId).once('value').then(snap => {
//const token = snap.child("messaging_token").val();
const token = event.data.child('receiverToken').val();
console.log("token: ", token);
//we have everything we need
//Build the message payload and send the message
console.log("Construction the notification message.");
const payload = {
data: {
data_type: "direct_message",
title: "New Message from " + senderName,
message: message,
message_id: messageId,
}
};
return admin.messaging().sendToDevice(token, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
//using this return statement to avoid error
return response.successCount;
})
.catch(function(error) {
console.log("Error sending message:", error);
});
});
});
});
我已經做了一些測試,並且文檔中DataSnapshot
對象中沒有屬性data
。 由於這個調用,它將給出undefined
值。 因此,如果您對此進行任何調用,則會導致此類錯誤。
如果您將...snapshot.data.child('senderUid').val()...
更改為:
...snapshot.child('senderUid').val()...
不確定您為什么在此處添加此data
,但是即使您在引用的路徑中有名為“data”的子項,它也不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.