user3711175
user3711175

Reputation: 109

Firebase update data not working

Hi I wanted to update the firebase data, but when I update it insert to a new data instead of updating the specific data that I set which is the lastname equal to 'hoo'

fb.orderByChild("Lastname").equalTo('hoo').once("value", function(snapshot){
  console.log(snapshot.ref());
  console.log(snapshot.val());
  // var snapref = snapshot.ref();
  snapshot.ref().update({
    FirstName: 'yoyo1'  
  });
})

Edit:

fb.orderByChild("Lastname").equalTo('hoo').once("child_added", function(snapshot){
    console.log(snapshot.ref());
    console.log(snapshot.val());
    // var snapref = snapshot.ref();
    snapshot.ref().update({
      FirstName: 'yoyo1'      
    });  
  })

enter image description here

See the bottom code the new edit code that works by using 'child_added' not using value

Upvotes: 0

Views: 3416

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598688

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

This means that when you call snapshot.ref(), you get the reference to the location that you queried (fb) not to the child that you selected.

The solution is to loop over the results:

fb.orderByChild("Lastname").equalTo('hoo').once("child_added", function(snapshot){
    snapshot.forEach(function(child) {
        child.ref().update({
            FirstName: 'yoyo1'      
        });  
    }
})

By the way, I'm pretty sure I gave the exact same answer in the past few days. So I highly recommend lurking on the firebase-database tag and learning while you read what others struggle with.

Upvotes: 1

Related Questions