Red M
Red M

Reputation: 2789

Obtain raw value "val()" data of parent node from a child reference in Cloud Functions Realtime Database

Let's say I'm pointing at a path as follow in my typescript/javascript code function:

exports.sendNotification = functions.database.ref('shops/countries/{countryName}/shopAddress/{currentShopAddress}')
.onWrite((snapshot,context) => {

    // Is it possible to get the data raw value from a child reference node? 
    // For example: 
    const countryName = snapshot.before.parent('countryName').val();
    // Then
    const countryId = countryName['countryId'];
})

I'm a node.js/typescript and firebase cloud functions newbie :)

Upvotes: 1

Views: 120

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

The data for parent nodes from the database is not automatically passed into your Cloud Function, as that you be a potentially large amount of unneeded data.

If you need it, you'll need to load it yourself. Luckily this is not all that hard:

const countryRef = snapshot.ref.parent.parent;
const countryName = countryRef.key; // also available as context.params.countryName
countryRef.child('countryId').once('value').then((countryIdSnapshot) => {
  const countryId = countryIdSnapshot.val();
});

Note that, since your asynchronously loading additional data, you'll need to return a promise to ensure your function doesn't get shut down prematurely.

Upvotes: 1

Related Questions