简体   繁体   中英

I am getting this kind of error “TypeError: Cannot read property 'data' of undefined at deviceToken.then.result (/srv/index.js:14:33)” at node.js

Here is my code:

    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');

        });
    });


});

And I am getting this error:

TypeError: Cannot read property 'data' of undefined at deviceToken.then.result (/srv/index.js:14:33)

I am to retrieve device token id from users. How would I do that?

node --version: v12.4.0 npm --version: 6.9.0

The once method inside firebase.database.Reference returns a Promise<DataSnapshot> . The class admin.database.DataSnapshot does not contain a property called after . If you are trying to retrieve the token from the database then change the following:

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

into this:

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

From the docs:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM