Proper way to store values array-like in Firebase
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'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.
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');
})