Firebase: HowTo update the value item of a record without knowing its unique id?

心已入冬 提交于 2019-12-25 04:29:23

问题


So, I have a firebase structure as follows:

"Posts" : {
  "0" : {
      "code": 12345TG4
      "Likes" : 59
  },
  "1" : {
      "code": RT560451
      "Likes" : 12
  }
}

Ideally what I want to do is:

var updateData = {
  Likes: 74
}

Posts.child(id).update(updateData);

But I don't know the UiD in advance, but I do have the value of the 'code', which is itself a unique value.

How do I create a query which can update the value 'Likes' based on the known value of 'code' in Firebase?


回答1:


As Doug commented and Rodrigo showed, you'll have to first query for the item based on its code, before you can update it:

var ref = firebase.database().ref();
ref.child("Posts").orderByChild("code").equalTo("12345TG4").once("value", function(snapshot) {
    snapshot.forEach(function(child) {
        child.ref.update(updateData);
    });
});

Change your model

Although the above will work, you should consider why you're storing your posts under an array index, then they also have a unique ID already. It is more idiomatic in NoSQL solutions such as Firebase to store the posts under the code:

"Posts" : {
  "12345TG4" : {
      "Likes" : 59
  },
  "RT560451" : {
      "Likes" : 12
  }
}

Which you'd update with:

ref.child("Posts").child("12345TG4").update({ Likes: 74 });

Or even:

"PostLikes" : {
  "12345TG4" :  59,
  "RT560451" :  12
}

And then:

ref.child("PostLikes/12345TG4/Likes").set(74);



回答2:


Try to do this.

var ref = firebase.database().ref("Posts");
ref.orderByChild("code").on("child_added", function(snapshot) {
        snapshot.ref.update(updateData);
});

Best regards



来源:https://stackoverflow.com/questions/42102398/firebase-howto-update-the-value-item-of-a-record-without-knowing-its-unique-id

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