2

我有一個messages條目,看起來像這樣:更新在谷歌雲的變化火力地堡觸發器的裁判功能

firbaseapp 
messages 
    -KiG85eYMH7jfKph4bl3 
     created: 1492788734743 
     title: "title" 
     message: "message" 

我想給當新的條目添加到這個列表中,以便 我添加了一個通知這個雲功能:

exports.sendMessageNotification = functions.database.ref('/messages/').onWrite(event => { 

    event.data.forEach(message => { 

     if (message.val().notificationSent) { 
      return; 
     } 

     admin.messaging().sendToTopic(...) 
     .then(res => { 
      return db.ref('/messages').child(message.key).update({ 
       notificationSent: (new Date()).getTime(), 
      }); 
     }) 
    }); 
}); 

問題是message.keymessages-KiG85eYMH7jfKph4bl3所以當我試圖挽救它,它會創建一個新的條目,而不是更新現有的一個:

firbaseapp 
messages 
    -KiG85eYMH7jfKph4bl3 
     created: 1492788734743 
     title: "title" 
     message: "message" 
    -messages-KiG85eYMH7jfKph4bl3 
     notificationSent: 123434554534 

我想要的是在現有條目上設置notificationSent

我也試過使用message.ref但我得到了同樣的結果。

那麼什麼是最好的方式來更新雲功能的firebase中的列表項?

+0

任何理由,你爲什麼不能簡單地在'/消息/ {MESSAGEID}'觸發?所以'functions.database.ref('/ messages/{messageId}')'。 –

+0

當我調用'push()'時,由firebase生成消息ID,所以問題是 - 如何從更改中獲取消息ID? – haki

+1

'const messageId = event.params.messageId' –

回答

3

我想這完成你想做的事,並回答你的問題的意見:

exports.sendMessageNotification = functions.database.ref('/messages/{messageId}') 
    .onWrite(event => { 
    const messageId = event.params.messageId; 
    console.log('messageId=', messageId); 

    if (event.data.current.child('notificationSent').val()) { 
     console.log('already sent'); 
     return; 
    } 

    const ref = event.data.ref; // OR event.data.adminRef 

    admin.messaging().sendToTopic(...) 
     .then(res => { 
      return ref.update({ 
       // Caution: this update will cause onWrite() to fire again 
       notificationSent: (new Date()).getTime(), 
      }); 
     }) 
});