Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions for Firebase: How to get event.data.ref.parent.child("xxx").val?

I'm having a structure on Firebase like this:

members
 |- -kSjJSDFjl2DFc
          |- isDeleted: true
          |- gender: "male"

In my cloud function, I wrote:

exports.doMemberDeletion = functions.database.ref("/members/{memberId}/isDeleted").onWrite(event => {
    const isDeleted = event.data.val();

    if (isDeleted) {
        const gender = event.data.ref.parent.child("gender").val; // Error here
        console.log("Deleted a " + gender + " member");
    }
});

However, it gives error on event.data.ref.parent.child().val, please advise how to get the value in this case. Thanks!

like image 936
Softhinker.com Avatar asked Dec 08 '22 18:12

Softhinker.com


2 Answers

The DeltaSnapshot provided in the event data is for the matched location only. Data higher in the tree or in siblings is not available. If your member data is not so large that you're concerned about listening for changes to any of it, you could do this:

// listen one level higher in tree    
exports.doMemberDeletion = functions.database.ref("/members/{memberId}").onWrite(event => {
    const wasDeleted = event.data.previous.child('isDeleted').val();
    const isDeleted = event.data.current.child('isDeleted').val();

    if (!wasDeleted && isDeleted) {
        const gender = event.data.current.child('gender').val();
        console.log("Deleted a " + gender + " member");
    }
});

Your original approach also works, but requires a fetch of the gender data:

exports.doMemberDeletion = functions.database.ref("/members/{memberId}/isDeleted").onWrite(event => {
    const isDeleted = event.data.val();

    if (isDeleted) {
        // as noted in Jen Person's answer, use adminRef for unrestricted access
        return event.data.adminRef.parent.child('gender').once('value').then((snapshot) => {
           console.log("Deleted a " + snapshot.val() + " member");
        });
    }
});
like image 118
Bob Snyder Avatar answered Apr 19 '23 23:04

Bob Snyder


Does the user have permission to access the parent? If not, instead of event.data.ref, use event.data.adminRef to have unrestricted access to the database. See the documentation for more information.

like image 43
Jen Person Avatar answered Apr 20 '23 00:04

Jen Person