Ad

How To Change Values Inside New Firebase OnUpdate Or OnWrite Triggers?

Before version (<= v0.9.1) it was possible to set data like that and now not anymore...

event.data.ref.child('thisname').set("error");

edit: setter are not mentioned here! Only how to receive values from onUpdate or onWrite https://firebase.google.com/docs/functions/beta-v1-diff

Solution is posted below

Ad

Answer

Firebase: (supports version 1.0 or 2.0)

If someone else has problems changing / setting / updating values in his cloud functions inside an onUpdate or onWrite trigger, then this might help u...

First this is how my data tree looks like:

"users" : {
    "4h23u45h23509hu346034h5943h5" : {
      "address" : "Backouse 2",
      "city" : "Los Angeles",
      "name" : "Joseph",
       ...
    },
    "23u4g24hg234h2ui342b34hi243n" : {
      "address" : "Streetouse 13",
      "city" : "Los Angeles",
      "name" : "Stefan",
      ...

Now to the cloud functions:

Before (<= v0.9.1)

exports.updatingUser = functions.database.ref('/users/{pushId}')
.onUpdate(event => {
  var address = event.data.child('address');
  var city = event.data.child('city');

  if (address.changed() || city.changed()) {
      //generateThisname()
      if (thisname == null) {
        event.data.ref.child('name').set("error");     //Important Part
      }
      else {
        event.data.ref.child('name').set(thisname);    //Important Part
      }
      ...

Now (>= v1.0.0)

exports.updatingUser = functions.database.ref('/users/{pushId}')
.onUpdate((change, context) => {
  var addressBefore = change.before.child('address').val();
  var addressAfter = change.after.child('address').val();

  var cityBefore = change.before.child('city').val();
  var cityAfter = change.after.child('city').val();

  //create reference from root to users/{pushId}/
  var rootSnapshot = change.after.ref.parent.child(context.params.pushId)


      if ((addressBefore !== addressAfter) || (cityBefore !== cityAfter)) {
          //generateThisname()
          if (thisname === null) {
              rootSnapshot.child('name').set("error");
          }
          else {   
              rootSnapshot.child('name').set(thisname);
          }
          ...

So before you can set a value, you first have to make a reference from the root of your database and then go all the way down to you value and call set()

Ad
source: stackoverflow.com
Ad