Skip to content Skip to sidebar Skip to footer

Firebase: Howto Update The Value Item Of A Record Without Knowing Its Unique Id?

So, I have a firebase structure as follows: 'Posts' : { '0' : { 'code': 12345TG4 'Likes' : 59 }, '1' : { 'code': RT560451 'Likes' : 12 } } Ideally

Solution 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);

Solution 2:

Try to do this.

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

Post a Comment for "Firebase: Howto Update The Value Item Of A Record Without Knowing Its Unique Id?"