在 Firebase 中存储类似数组的值的正确方法 [英] Proper way to store values array-like in Firebase

查看:20
本文介绍了在 Firebase 中存储类似数组的值的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这首歌的名字,我正在为它保存评分.它看起来像下面的图片,因为我使用 push() 来存储每个新评级.

I have a name of the song, with ratings I am saving for it. And it looks like pic bellow, as I am using push() to store each new rating.

但我想看到的是,ratings 作为一个数组对象,每个对象都包含如下内容:

But what I would like to see is, ratings as an array of objects, each containing something like this:

voter: {
    ip: "1.1.1.1",
    stars: 3,
}

所以 rating 键最终会是这样的:

So rating key would end up being something like this:

rating: [{ip: "1.1.1.1", stars: 3}, ...]

然后我只能为每个 IP 地址启用一票.我找不到的东西Firebase 文档,是如何添加到现有密钥,在这种情况下 rating(但它会是 [list, like]) - 一个新的 hash 就像上面的那个.因为 push() 自动创建 hash-key 值,我想追加到现有密钥.

Then I can enable only one vote per IP address. What I couldn't find in Firebase docs, is how to add to an existing key, in this case rating(but it would be [list, like]) - a new hash like the one above. Because push() automatically creates hash-key value, and I want to append to an existing key.

我知道这一事实,Firebase 本身并不存储数组,但在这种情况下,这无关紧要,这只是我希望如何查看我的数据.

I am aware of the fact, that Firebase does not store arrays natively, however in this case it does not matter, it's just how I would like to see my data.

推荐答案

您当前正在使用 push 添加新的子节点,它会自动为保证"的新节点生成一个名称在多个客户端中是唯一的.

You are currently using push to add new children, which automatically generates a name for the new node that is "guaranteed" to be unique across multiple clients.

ref.push({ ip: userIP, stars: userStars });

Firebase 的 push 方法是让多个客户端向有序集合添加项目的好方法.如果要使用数组完成相同的操作,则必须在客户端之间同步数组的长度.Firebase 的名称生成不需要这样的开销,因此通常首选在多个客户端之间保存订单集合.

Firebase's push method is a great way to have multiple clients adding items to an ordered collection. If you want to accomplish the same using arrays, you'd have to synchronize the length of the array between the clients. Firebase's name generation doesn't require such overhead, so is normally the preferred of keeping an order collection across multiple clients.

但就您而言,您似乎不想要有序的仅追加"集合.您似乎认为 IP 地址是每个节点的标识.在这种情况下,我将使用 IP 地址作为节点名称的基础:

But in your case, you don't seem to want an ordered "append only" collection. It seems like you consider the IP address to be an identification of each node. In that case I would use the IP address as the basis for the node name:

votes
  "1.1.1.1": 3
  "1.2.3.4": 5
  "1.7.4.7": 2

您可以通过以下方式实现:

You would accomplish this with:

ref.child(userIP).set(userStars);

如果你想随后将所有投票读入一个数组,你可以这样做:

If you want to subsequently read all votes into an array, you can do:

var votes = [];
votesRef.on('value', function(snapshot) {
    snapshot.forEach(function(vote) {
        votes.push({ ip: vote.key, stars: vote.val() });
    });
    alert('There are '+votes.length+' votes');
})

这篇关于在 Firebase 中存储类似数组的值的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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