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.
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,
}
So rating
key would end up being something like this:
rating: [{ip: "1.1.1.1", stars: 3}, ...]
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.
EDIT: 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.
We could create this data by sending the following JSON tree to the player's collection. This is because Firebase does not support Arrays directly, but it creates a list of objects with integers as key names.
As a default Firebase database has no security, it's the development team's responsibility to correctly secure the database prior to it storing real data. In Google Firebase, this is done by requiring authentication and implementing rule-based authorization for each database table.
Firebase Realtime Database is a NoSQL cloud database that is used to store and sync the data. The data from the database can be synced at a time across all the clients such as android, web as well as IOS. The data in the database is stored in the JSON format and it updates in real-time with every connected client.
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');
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With