0

log result獲得「未定義」快照值

inside of the log error 我目前在建立我的火力地堡雲功能有一個用戶到用戶推送通知的過程中,每次有新的孩子加入到「信息」。對於每個用戶,存在存儲在該結構中「/用戶/ UID /令牌」一個節點的通知。然而,在我的火力地堡日誌安慰它變成了那個被返回的值是「未定義」。這是我第一次用Node.js的工作,所以一切都非常新。任何幫助,將不勝感激。這裏是什麼功能

const functions = require('firebase-functions'); 

const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 

// Listens for new messages added to messages/:pushId 
exports.messageWritten =  functions.database.ref('/messages/{pushId}').onWrite(event => { 

console.log('Push notification event triggered'); 

// Grab the current value of what was written to the Realtime Database. 
var valueObject = event.data.val(); 
console.log(valueObject.text,valueObject.toId); 

return admin.database().ref(`/Users/${valueObject.toId}`).once('value').then(snapshot =>{ 
    console.log('the users name',snapshot.name) 
    console.log('the users token',snapshot.token) 
}) 


// Create a notification 
const payload = { 
    notification: { 
     title:snapshot.name +' sent you a message', 
     body: valueObject.text, 
     sound: "default" 
    }, 
}; 

//Create an options object that contains the time to live for the notification and the priority 
const options = { 
    priority: "high", 
    timeToLive: 60 * 60 * 24 
}; 


    return admin.messaging().sendToDevice(snapshot.token, payload, options); 
}); 

回答

0

內您的函數的兩個return語句。第一return語句後的代碼(發送消息)將不會運行。

const functions = require('firebase-functions'); 

const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 

// Listens for new messages added to messages/:pushId 
exports.messageWritten = functions.database.ref('/messages/{pushId}').onWrite(event => { 

    console.log('Push notification event triggered'); 

    // Grab the current value of what was written to the Realtime Database. 
    var valueObject = event.data.val(); 
    console.log(valueObject.text, valueObject.toId); 

    return admin.database().ref(`/Users/${valueObject.toId}`).once('value').then(snapshot => { 
     console.log('the users name', snapshot.val().name) 
     console.log('the users token', snapshot.val().token) 

     // Create a notification 
     const payload = { 
      notification: { 
       title: snapshot.val().name + ' sent you a message', 
       body: valueObject.text, 
       sound: "default" 
      }, 
     }; 

     //Create an options object that contains the time to live for the notification and the priority 
     const options = { 
      priority: "high", 
      timeToLive: 60 * 60 * 24 
     }; 

     return admin.messaging().sendToDevice(snapshot.val().token, payload, options); 
    }) 
}); 
+0

我只是想你建議的代碼,但它仍然快到了爲未定義,我提供的是在問題發生的截圖 – oneQuestionAsker

+0

呀,'snapshot.token'將無法正常工作。你可能需要'snapshot.val()。token'。強烈建議您閱讀[Firebase文檔](https://firebase.google.com/docs/database/admin/start),然後再繼續操作。在那裏度過了幾個小時,將節省您大量的時間和許多堆棧溢出問題的路線。 –