简体   繁体   中英

Firebase Realtime Database and Cloud Functions: observe child of user returns undefined when attempting event value

I have a user table in firebase real time database wit fields:

userKey
  - uid
  - emailVerfied
  - attempts

I would like to observe changes in userKey/attempts field, I have the following trigger setup:

 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}`);

})

This function is triggered each time the field attempt is updated, however it evidently cannot retrieve record.uid as I intended, because the email sent looks like this:

delivered from realtime.onUpdate with user undefined

What is the right way to retrieve a snapshot of the database' value?

With your current code and data structure, the value of uid in '/users/{uid}/attempts' will actually be userKey , and not the value of the sub-node uid of userKey .

And to get this value in your Cloud Function code you should do

 event.params.uid 

since you are using a version of the Firebase SDK for Cloud Functions which is <1.0.0 (see below)


If, on the opposite, you want to get the value of uid and not the one of userKey , you should listen at the upper level, as follows:

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

I would then suggest that you upgrade your code to v1.0.0 (see the doc here ) and then do as follows:

 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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM