javascript - Firebase 实时云功能 - 无法读取空快照的属性
问题描述
我经历了所有类似的答案,但没有运气,但由于某种原因,我的 Firebase 云函数返回 null 的 snapshot.val()。第一个 console.log 打印正确,给出以下内容:
用户:8Ch7RGBnMrNiQlS6g8xKcDO3cr93 关注:WpKoFs1UgHTCZegMwjkXyXqrBTz1
我将在底部附上数据库的结构。这是我得到的错误:
TypeError:无法在 admin.database.ref.once.snapshot 读取属性“fcmToken”的 null
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()
当您请求的位置没有数据时将为空,这里肯定是这种情况。
此处指定了“/users/{followingId}”的查询位置:
admin.database().ref('/users/{followingId}')
该字符串是按字面意思理解的。这里没有进行变量替换。如果您想放入followingId
该字符串,您需要告诉 JavaScript 正确执行此操作:
admin.database().ref(`/users/${followingId}`)
请注意字符串分隔符的反引号以及指定要包含在字符串中的值的方式。
您可能混淆了函数定义的占位符语法。
推荐阅读
- c# - 排序后无法在datagridview的特定索引中插入一行
- python-3.x - 在这样的短期课程中上课有什么好处
- python - 在具有不同大小和相似匹配的字符串中查找完全匹配
- c# - 如何更改按钮事件中标签的文本?
- html - 在不同类型的按钮之间切换
- php - 使用 google 联系人 api 更改联系人的问题
- git - “git log --diff-filter=R”和“git log --find-renames”有什么区别?
- javascript - Chrome 性能 DevTools 中不明确的“任务”
- javascript - 如何在 React Native 中创建 64 位 apk
- javascript - JavaScript 开始使用正则表达式和偏移量