【问题标题】:Firebase Realtime Cloud Function - Cannot read property of null snapshotFirebase 实时云功能 - 无法读取空快照的属性
【发布时间】:2019-03-21 01:04:47
【问题描述】:

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

})

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

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

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

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

    【讨论】:

    • 谢谢 Doug,但是您确定 Firebase Cloud 功能就是这种情况。即使在他们的文档和我看过的许多其他示例中,也不需要字符串分隔。使用此方法实际上会导致更多错误,因为第一个控制台日志不再打印。 firebase.google.com/docs/functions/database-events
    • 我很积极。这是一个常见的错误。正如我在答案的最后所说,您可能会混淆函数定义的占位符语法。它与 JavaScript 字符串插值不同。
    猜你喜欢
    • 1970-01-01
    • 2018-12-05
    • 2020-05-18
    • 2021-07-15
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    相关资源
    最近更新 更多