代码之家  ›  专栏  ›  技术社区  ›  xiaolingxiao

FireBase实时数据库和云函数:观察用户的子级在尝试事件值时返回未定义

  •  0
  • xiaolingxiao  · 技术社区  · 7 年前

    我在FireBase实时数据库WIT字段中有一个用户表:

    userKey
      - uid
      - emailVerfied
      - attempts
    

    我想观察一下 userKey/attempts 字段,我有以下触发器设置:

     export const onUpdate = functions.database
    .ref('/users/{uid}/attempts').onUpdate( event => {
    
        const record = event.after.val();
    
        // sending an email to myself, 
        adminLog(
              `user ${record.email} requested a new confirmation email`
            , `delivered from realtime.onUpdate with user ${record.uid}`);
    
    })
    

    每次字段 attempt 已更新,但显然无法检索 record.uid 正如我预期的那样,因为发送的电子邮件如下所示:

    delivered from realtime.onUpdate with user undefined
    

    检索数据库值快照的正确方法是什么?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Renaud Tarnec    7 年前

    使用当前的代码和数据结构, uid 在里面 '/users/{uid}/attempts' 实际上 userKey ,而不是子节点的值 用户界面 属于 用户密钥 .

    为了在你的云函数代码中得到这个值,你应该这样做

     event.params.uid 
    

    因为您使用的是FireBase SDK的云功能版本,即<1.0.0(见下文)


    相反,如果你想得到 用户界面 而不是 用户密钥 ,你应该在上面听,如下:

    export const onUpdate = functions.database.ref('/users/{userKey}').onUpdate(...)   //I just changed, for clarity, to userKey, instead of uid
    

    然后我建议您将代码升级到v1.0.0(请参阅文档 here )然后按如下步骤进行:

     functions.database.ref('/users/{userKey}').onUpdate((change, context) => {
      const beforeData = change.before.val(); // data before the update
      const afterData = change.after.val(); // data after the update
    
      //You can then check if beforeData.attempts and afterData.attempts are different and act accordingly
    
      //You get the value of uid with: afterData.uid
    
      //You get the value of userKey (from the path) with: context.params.userKey
    
    });