Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "snapshot.val" is not a function in Google Cloud Functions

When creating a new node, I want to create and push that same data into a different node.

The "ins" node is the node I am pushing the new data into:

root: { 
  doors: {
    111111111111: {
       MACaddress: "111111111111",
       inRoom: "-LBMH_8KHf_N9CvLqhzU",
       ins: {
          // I am creating several "key: pair"s here, something like:
          1525104151100: true,
          1525104151183: true,
       }
    }
  },
  rooms: {
    -LBMH_8KHf_N9CvLqhzU: {
      ins: {
        // I want it to clone the same data here:
        1525104151100: true,
        1525104151183: true,
      }
    }
  }

My function code is the following but it's not working at all. I can't even start the function when I use the onCreate trigger (which is all I need). Any ideas on how to make this work?

exports.updateRoom = functions.database.ref('doors/{MACaddress}/ins')
.onCreate((snapshot, context) => {
    const timestamp = snapshot.val();
    const roomPushKey = functions.database.ref('doors/{MACaddress}/inRoom');
    console.log(roomPushKey);  
    return snapshot.ref.parent.parent.child('rooms').child(roomPushKey).child('ins').set(timestamp);
});  

Note: I have fiddled with the code and I got it to run by changing the trigger to onWrite but like this I get an error message: "snapshot.val" is not a function...

exports.updateRoom = functions.database.ref('doors/{MACaddress}/ins').onWrite((snapshot, context) => {     
    const timestamp = snapshot.val();
    const roomPushKey = functions.database.ref('doors/{MACaddress}/inRoom');
    console.log(roomPushKey);
    return snapshot.ref.parent.parent.child('rooms').child(roomPushKey).child('ins').set(timestamp);
});  
like image 673
Joao Alves Marrucho Avatar asked Dec 02 '22 10:12

Joao Alves Marrucho


1 Answers

If you are using onWrite, you have to do the following:

exports.dbWrite = functions.database.ref('/path').onWrite((change, context) => {
 const beforeData = change.before.val(); // data before the write
 const afterData = change.after.val(); // data after the write
});

onWrite is used when any changes happen in the specified path, so you can retrieve the before the changes and after the changes.

more info here:

https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database

https://firebase.google.com/docs/reference/functions/functions.Change

In onCreate, you can do this:

exports.dbCreate = functions.database.ref('/path').onCreate((snap, context) => {
const createdData = snap.val(); // data that was created
});

Since onCreate is triggered when you add new data to the database.

like image 193
Peter Haddad Avatar answered Dec 04 '22 04:12

Peter Haddad