首页 > 解决方案 > 我在 node.js 处收到这种错误“TypeError:无法读取 deviceToken.then.result (/srv/index.js:14:33) 处未定义的属性‘数据’”

问题描述

这是我的代码:

    const deviceToken = admin.database().ref(`/users/{sender_user_id}/token_id`).once('value');

    return deviceToken.then(result => {
        const token_id = result.after.data();

        const payload = {
            notification: {
                title: "New message!",
                body: "You have a new message!",
                icon: "default"
            }
        };

        return admin.messaging().sendToDevice(token_id, payload).then(response => {
            return console.log('This was a notification');

        });
    });


});

我收到了这个错误:

TypeError:无法读取 deviceToken.then.result (/srv/index.js:14:33) 处未定义的属性“数据”

我要从用户那里检索设备令牌 ID。我该怎么做?

节点 --version: v12.4.0 npm --version: 6.9.0

标签: javascriptfirebasefirebase-realtime-databasefirebase-cloud-messaging

解决方案


里面的once方法firebase.database.Reference返回一个Promise<DataSnapshot>. 该类admin.database.DataSnapshot不包含名为 的属性after。如果您尝试token从数据库中检索 ,请更改以下内容:

    return deviceToken.then(result => {
        const token_id = result.after.data();

进入这个:

    return deviceToken.then(result => {
        const token_id = result.val();

从文档:

val

从 DataSnapshot 中提取 JavaScript 值。

根据 DataSnapshot 中的数据,该val()方法可能返回标量类型(字符串、数字或布尔值)、数组或对象。它也可能返回 null,表示DataSnapshot为空(不包含数据)。


推荐阅读