javascript - Firebase Realtime Cloud Function - 无法读取空快照的属性

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

我已经浏览了所有类似的答案,但没有运气,但由于某种原因,我的 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);
    });
})

}) enter image description here

最佳答案

当您请求的位置没有数据时,

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/

相关文章:

java - 无法从Firebase存储中自动检索图像

javascript - 将 Firebase 与 Webpack 和 TypeScript 结合使用

java - Google Firebase 实时数据库无法正常工作,因为一切都已正确设置

javascript - addeventlistener 多次构建

javascript - JSONP 使用 Google Apps 脚本的 ContentService?

javascript - 如何将 C# DateTime 与 Javascript 的 Date.now() 进行比较

javascript - Ajax 数组不会在下拉选择时填充

javascript - 如何在客户端绑定(bind)之前对 SAPUI5 OData 进行分组以进行控制?

ios - 从 FIRRemoteConfigValue 转换为不相关的类型 String 总是失败 : Firebase, Swift

ios - 如何检查 childByAutoID() 是否已存在于 Firebase 实时数据库中?