Firebase update data not working

丶灬走出姿态 提交于 2020-01-06 19:51:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!