我已经浏览了所有类似的答案,但没有运气,但由于某种原因,我的 Firebase 云函数返回 null 的 snapshot.val()。第一个 console.log 正确打印,给出以下内容:
User:8Ch7RGBnMrNiQlS6g8xKcDO3cr93 is following: WpKoFs1UgHTCZegMwjkXyXqrBTz1
我会在底部附上数据库的结构。这是我得到的错误:
TypeError: Cannot read property 'fcmToken' of null at admin.database.ref.once.snapshot
exports.observeFollowing = functions.database.ref('/users/{uid}/following/{followingId}').onCreate((context) => {
var uid = context.params.uid
var followingId = context.params.followingId
console.log('User:' + uid + ' is following: ' + followingId)
return admin.database().ref('/users/{followingId}').once('value', snapshot => {
console.log(snapshot.val())
var userWeAreFollowing = snapshot.val()
var message = {
notification: {
title: "You have a new follower",
body: "It's Tom"
},
token: userWeAreFollowing.fcmToken
};
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
return response
}).catch((error) => {
console.log('Error sending message:', error);
});
})
最佳答案
当您请求的位置没有数据时,
snapshot.val()
将为 null,这里肯定是这种情况。
此处指定了“/users/{followingId}”的查询位置:
admin.database().ref('/users/{followingId}')
该字符串按字面意思理解。这里没有进行变量替换。如果您想将 followingId
放入该字符串中,您需要告诉 JavaScript 正确执行此操作:
admin.database().ref(`/users/${followingId}`)
请注意字符串分隔符的反引号以及指定要包含在字符串中的值的方式。
您可能混淆了函数定义的占位符语法。
关于javascript - Firebase Realtime Cloud Function - 无法读取空快照的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55272330/