Reputation: 118
I am trying to calculate the product rating for my products in my realtime database using a firebase cloud function. What am I missing since am getting errors in the logs after deploying
I have deployed the code but still on rating added no change happens
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//firebase db calculations for rating average
exports.productAverage = functions.database.ref('/Products/{product_id}/rating')
.onCreate((snapshot, context) => {
return admin.database().ref('/Products/{product_id}/rating').once('value')
.then((snapshot) => {
let sum = 0;
snapshot.forEach(child => {
sum = sum + child.val();
});
let productRating = sum / snapshot.numChildren();
return admin.database().ref('/Products/{product_id}').child('productRating').set(productRating);
});
});
I expect each time a productRating node is added, the average updates a node on the database with productRating
Upvotes: 1
Views: 121
Reputation: 599121
There are a few things that immediately jump out:
onCreate
. But you want to recalculate the average whenever any rating is added (or removed or updated), you'll want to trigger on onWrite
.With these two changes, you'd end up with something like:
exports.productAverage = functions.database.ref('/Products/{product_id}/rating')
.onWrite((change, context) => {
let snapshot = change.after;
let sum = 0;
snapshot.forEach(child => {
sum = sum + child.val();
});
let productRating = sum / snapshot.numChildren();
return snapshot.ref.parent.child('productRating').set(productRating);
});
Upvotes: 3