首页 > 解决方案 > 在 Firebase 中使用 onUpdate 函数时,如何检索返回的快照的子节点?

问题描述

我有过去使用 .onCreate 运行的波纹管代码,我将其更改为 .onUpdate,现在 .child() 行出现错误,表明我无法执行该操作。我该如何进行?我需要访问这些值。

   export const sendNewMessageNotification = functions.database
  .ref('/ChatTimelines/{uid}/{chatID}/')
  .onUpdate((snapshot, context) => {
    //.onCreate
    const uid = context.params.uid
    const otherUID = snapshot.child("otherUID").val()//error
    const message = snapshot.child("lastMessage").val()//error
    snapshot
  
    //addNewLikeNotif(uid, newLikerUID, mediaNumber, timeStamp, postID)
    return sendNewMessageNotificationFunc(uid, otherUID, message) 
  })

更新:Update2 这不起作用

(变化,上下文)

 let snapshot = change.after.val()
const otherUID = snapshot.child("otherUID").val()
const message = snapshot.child("lastMessage").val()

标签: typescriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


如果您使用onUpdate,则需要执行以下操作:

  .onUpdate((snapshot, context) => {
    const uid = context.params.uid
    const otherUID = snapshot.after.child("otherUID").val();
    const message = snapshot.after.child("lastMessage").val();

检查文档:

https://firebase.google.com/docs/functions/beta-v1-diff#sdk_changes_by_trigger_type


推荐阅读