简体   繁体   中英

Cloud Functions for Firebase: how to reference a key in a list that has been just pushed

My question is basically what to do in your cloud function, if you want to reference keys that have been generated when the client called push().

/providerApps/{UID}/ is my path to a list of appointment nodes, so each appointment node is at /providerApps/{UID}/someKey .

I need the "new item in the list", the one that was added with push(), so I thought I could order the keys and simply get the last one, but that does not work:

// (Try to) Listen for new appointments at /providerApps/{pUID}
// and store the appointment at at /clientApps/{cUID}
// cUID is in the new appointment node
exports.storeNewAppForClient = functions.database.ref("/providerApps/{UID}").onWrite(event => {

      // Exit when the data is deleted.
      if (!event.data.exists()) {
        console.log("deletion -> exiting");
        return;
      }

      const pUID = event.params.UID;
      const params = event.params;
      console.log("params: ", params);

      const firstAppVal = event.data.ref.orderByKey().limitToLast(1).val();
      // TypeError: event.data.ref.orderByKey(...).limitToLast(...).val is not a function 

      const date = firstAppVal["dateStr"];
      const cUID = firstAppVal["clientUID"];

    return event.data.ref.root.child("clientApps").child(cUID).child(date).set(pUID);
});

I guess I could do it on the client side with push().getKey() and allow providers to write into clientApps node, but that seems to be less elegant.

Any ideas how to do this with cloud functions?

As an illustration, my data structure looks like this:

there are provider and their clients who make appointments

Cheers

Change your trigger location to be the newly created appointment instead of the list of appointments. Then you can access the appointment data directly:

exports.storeNewAppForClient = functions.database.ref("/providerApps/{UID}/{pushId}").onWrite(event => {
      // Exit when the data is deleted.
      if (!event.data.exists()) {
        console.log("deletion -> exiting");
        return;
      }

      const pUID = event.params.UID;
      const params = event.params;
      console.log("params: ", params);

      const date = event.data.child('dateStr').val();
      const cUID = event.data.child('clientUID').val();

    return admin.database().ref('clientApps').child(cUID).child(date).set(pUID);
});

(updated for Frank's comment)

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