Hey JD,
I think you can approach this in either of two ways.
Option 1:
If you need to store every rating for perpetuity, you can just put them in a /ratings/ node within each item, specifying the rating and the user ID of the user who made the rating. It would looks something like this:
{
items: {
$itemId: {
title: <title>,
...,
ratings: {
user1: 4,
user35: 3,
...
}
}
}
}
Then, when you want to get the total number of ratings and the average rating, you can do something like this:
var itemRef = rootRef.child("items").child(itemId);
var numRatings = 0;
var cumulativeRating = 0;
itemRef.child("ratings").on("child_added", function(ratingSnapshot) {
var uid = ratingSnapshot.key();
var ratingValue = ratingSnapshot.val();
numRatings++;
cumulativeRating += ratingValue;
});
The number of ratings will be numRatings and the average rating will be cumulativeRating / numRatings.
Option 2:
If you don't care about a specific user's rating, you can just keep track of the number of ratings and cumulative rating in Firebase itself. Your Firebase would look like this:
{
items: {
$itemId: {
title: <title>,
...,
ratings: {
numRatings: 58,
cumulativeRating; 176
}
}
}
}
Then, you can calculate get the number of ratings and the average rating like this:
var itemRef = rootRef.child("items").child(itemId);
var numRatings;
var cumulativeRating;
var averageRating;
itemRef.child("ratings").on("value", function(ratingsSnapshot) {
var ratingsData = ratingsSnapshot.val();
numRatings = ratingsData.numRatings;
cumulativeRating = ratingsData.cumulativeRating;
averageRating = cumulativeRating / numRatings;
});
Good luck,
Jacob