0

I'm currently trying to learn Firebase functions. This new feature seems to be pretty powerful and useful.

I'd like to use a function the catch a DB writing event, make a comparison with a specific location in DB and then write some data (depending on the comparison result) in another location in DB.

Here's my current Node.js code:

exports.verificaFineLavoro = functions.database.ref('/Aziende/{nomeazienda}/LogAsegno/{pushidbracciante}/{pushidlog}/Asegno')
.onWrite(event => {
  const original = event.data.val();
  console.log('VerificaFineLavoro', event.params.pushId, original);
  const aSegno = original;
  console.log('aSegno', aSegno +"");
  const FineLavoro = ref.parent.parent.parent.parent.child("Asegno/"+aSegno+"/FineLavoro");
  return event.data.ref.child('FL').set(FineLavoro);
});

Currently the function gets triggered but it stops working because of the references which are probably wrong.

2
  • If you already know that your references are wrong, what keeps you from fixing them? Commented Apr 4, 2017 at 13:18
  • I don't know how to make a reference inside a function and how to retrive data from it. The code i posted was an attemp. Commented Apr 4, 2017 at 13:29

1 Answer 1

4

The Cloud Functions for Firebase documentation on triggering from the database contains code snippets that show how to access other nodes in the database.

For example, this snippet sets a value as a sibling to the node that triggered the function:

return event.data.ref.parent.child('uppercase').set(uppercase);

Here's another snippet from the sample on counting child nodes:

exports.countlikechange = 
functions.database.ref('/posts/{postid}/likes/{likeid}').onWrite(event => {
  const collectionRef = event.data.ref.parent;
  const countRef = collectionRef.parent.child('likes_count');
  ...

To access the root of the database use event.data.ref.root (to access the root node with the permissions of the user that triggered the function) or event.data.adminRef.root (to access the root with full administrative permission).

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, I'm going to try it now ;)
How can i build a reference from the root of my db?
event.data.ref.root or event.data.adminRef.root
@L.Gangemi You can also do admin.database().ref('path/to/ref') to reference some other path.
Can i use more .parent in sequence? I'd like to get the event reference and go back to a node at the start
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.