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?
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);
});
});
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);
Try to do this.
var ref = firebase.database().ref("Posts");
ref.orderByChild("code").on("child_added", function(snapshot) {
snapshot.ref.update(updateData);
});
Best regards
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.