Firebase:如何在不知道其唯一ID的情况下更新记录的值项? [英] Firebase: HowTo update the value item of a record without knowing its unique id?

查看:42
本文介绍了Firebase:如何在不知道其唯一ID的情况下更新记录的值项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我的firebase结构如下:

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

但是我不预先知道UiD,但是我确实有'code'的值,它本身就是唯一的值.

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

如何创建一个查询,该查询可以基于Firebase中代码"的已知值来更新值喜欢"?

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

推荐答案

如Doug注释和Rodrigo所示,您必须先根据商品代码查询商品,然后才能对其进行更新:

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

更改模型

尽管上面的方法行得通,但您应该考虑为什么将帖子存储在数组索引下,然后它们也已经具有唯一的ID.在NoSQL解决方案(例如Firebase)中,习惯做法是将帖子存储在代码下:

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
  }
}

您要更新的内容:

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

甚至:

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

然后:

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

这篇关于Firebase:如何在不知道其唯一ID的情况下更新记录的值项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆