首页 > 解决方案 > 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);
    });
})

}) 在此处输入图像描述

标签: javascriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


snapshot.val()当您请求的位置没有数据时将为空,这里肯定是这种情况。

此处指定了“/users/{followingId}”的查询位置:

admin.database().ref('/users/{followingId}')

该字符串是按字面意思理解的。这里没有进行变量替换。如果您想放入followingId该字符串,您需要告诉 JavaScript 正确执行此操作:

admin.database().ref(`/users/${followingId}`)

请注意字符串分隔符的反引号以及指定要包含在字符串中的值的方式。

您可能混淆了函数定义的占位符语法。


推荐阅读