Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions for Firebase - get parent data from database trigger

Is there a clean built in way of directly referencing the data value of the node above the database trigger? I understand I can get a parent ref which I could then query for the value, but if there was a more concise way of doing this that would be great thanks.

For clarity, I want to use a child node within an object as a trigger, and when it occurs get the value of the parent object directly, to avoid the function being invoked when other changes are made to the parent object like so:

const parentObject = {
 triggerValue: 'I want the function to be triggered only on writes to this path',
 parentValue: 'But I also want this value',
}

Thanks

like image 836
Sam Matthews Avatar asked May 04 '17 13:05

Sam Matthews


2 Answers

I've googled for this answer like six times and keep having to re-implement the solution.

Here's how to get the parent data, post, from a child attribute, post.body, that's changed:

exports.doStuff = functions.database
  .ref("/posts/{postId}/body")
  .onWrite(event => {
    return event.data.ref.parent.once("value").then(snap => {
      const post = snap.val();
      // do stuff with post here
    });
  });
like image 134
cgenco Avatar answered Nov 12 '22 05:11

cgenco


You can use event.data.ref and event.data.adminRef to navigate the database. They are Reference objects and work exactly like they would if you were building a web app with Firebase on the client side. So, if using the parent property to navigate up a level works fine for you, then just use that. There's no additional special syntax.

like image 43
Doug Stevenson Avatar answered Nov 12 '22 06:11

Doug Stevenson