0

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

1 Answer 1

1

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.

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

2 Comments

This code doesn't run. First, there's a close parentheses missing on the second to last line. More importantly, I get an error message: "child.ref is not a function". I don't see how "child" is a Firebase reference.
Depending on your Firebase SDK version that might need to be firebase.ref (without parenthesis). I answered for 2.x (which OP seems to be using), you may be using 3.x where DataSnapshot.ref is a property instead of a function: firebase.google.com/docs/reference/js/….

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.