javascript - 我在 deviceToken.then.result (/srv/index.js :14:33)"at node. js

标签 javascript firebase firebase-realtime-database firebase-cloud-messaging

这是我的代码:

    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: Cannot read property 'data' of undefined at deviceToken.then.result (/srv/index.js:14:33)

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

节点--版本:v12.4.0 npm --版本:6.9.0

最佳答案

once 里面的方法 firebase.database.Reference 返回 Promise<DataSnapshot> 。类(class) 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

Extracts a JavaScript value from a DataSnapshot.

Depending on the data in a DataSnapshot, the val() method may return a scalar type (string, number, or boolean), an array, or an object. It may also return null, indicating that the DataSnapshot is empty (contains no data).

关于javascript - 我在 deviceToken.then.result (/srv/index.js :14:33)"at node. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56697656/

相关文章:

javascript - 如何将代码从 rxjs v5 转换为 rxjs v6 以进行 catch?

javascript - 在没有 jquery 的情况下获取其中包含特定元素的元素作为子元素

javascript - 在 $.post 中创建动态变量赋值 - JQuery

ios - 通过电子邮件注册用户接受重复的电子邮件(firebase-swift)

python - 如何通过 REST API 和 Python 将干净的数据插入 Firebase

swift - Firebase 查询找不到电子邮件地址?

javascript - 删除超过 2 小时的 firebase 数据

javascript - 调整窗口大小时,页面上的四个图像不会调整大小

java - 为什么条目在 Firebase 数据库中不断循环?

security - Firebase 数据库安全规则