3

Hello everyone I am getting weird behaviour here. I try to update one specific child node, when the user clicks a button. Here is my code:

var updates2 = {};
var offer = {
  minusAccandShare: 2,
}
updates2['/offerLight/' + keyReal] = offer;
updates2['/offer/' + keyReal] = offer;
return firebase.database().ref().update(updates2);

Everything is working fine the correct nodes are updated but while updating minusAccandShare everything else will be deleted

The structure is like:

offer
  jifdjsiavdas
    minusAccandShare: -6
    offerName: "Replacement"
    offerText: "You have the choice to..."
    ...

And it becomes

offer
  jifdjsiavdas
    minusAccandShare: 2

I used this approach like described in the firebase guides multiple times and it always worked like a charm. But there I created completly new nodes with a new key so there was nothing to be deleted.

Thanks everyone :D

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
A. Ilazi
  • 341
  • 2
  • 21

2 Answers2

5

What is actually happening in your code is the folowing:

You are writing entirely to the key thereby wiping off the whole properties in your dataset.

this

updates2['/offer/' + keyReal] = offer;

wipes out the whole data in that particular key.

Try this instead:

firebase.database().ref('offer/' + keyReal).update({
    minusAccandShare: 2,
  });

this allows you to make sure you change the specified property in your firebase dataset.

I hope this helped

  • Ebenezer is right. In this instance, while updating - even when utilizing the 'update' function rather than 'set' - the data object will be overwritten completely. I needed to pass my object after including the key as he's written above. – Mike Ferrari Jun 25 '17 at 22:27
1

Seems like you should read up on firebase refs. You don't seem to be updating the ref so you're updating (presumably) the root DB object (I have never passed a blank ref to Firebase so I'm not 100% sure what the behavior is of using firebase.database().ref().

I've "compiled" your code so you we can see what you're passing to the empty ref:

var updates2 = {};

updates2['/offerLight/' + keyReal] = offer;
updates2['/offer/' + keyReal] = offer;

// Becomes...

updates2 = {
  '/offerLight/jifdjsiavdas': {
    minusAccandShare: 2
  },
  '/offer/jifdjsiavdas': {
    minusAccandShare: 2
  }
}

// So...

return firebase.database().ref().update( updates2 );

// is sent as

return firebase.database().ref().update({
  '/offerLight/jifdjsiavdas': {
    minusAccandShare: 2
  },
  '/offer/jifdjsiavdas': {
    minusAccandShare: 2
  }
})

It seems like what you actually want to be doing is referencing the child node jifdjsiavdas. You'll want to point to it with a reference like this:

firebase.database.ref( 'offer/' + keyReal ).update( offer );
imjared
  • 19,492
  • 4
  • 49
  • 72