Firebase实时数据库和云功能:当尝试事件值时,观察用户的子代返回undefined

lb3vh1jj  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(95)

我在firebase真实的数据库中有一个用户表,它包含以下字段:

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

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

b5lpy0ml

b5lpy0ml1#

使用当前的代码和数据结构,'/users/{uid}/attempts'uid的值实际上是userKey,而不是userKey的子节点uid的值。
要在云函数代码中获取此值,您应该执行以下操作

event.params.uid

因为您使用的Firebase SDK for Cloud Functions版本〈1.0.0(请参阅下文)
相反,如果你想得到uid的值,而不是userKey的值,你应该在上层监听,如下所示:

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

});

相关问题