问题
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'
});
})
See the bottom code the new edit code that works by using 'child_added' not using value
回答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.
来源:https://stackoverflow.com/questions/42391928/firebase-update-data-not-working