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!
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");
});
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With