My db layout is:
@posts
@postId_abc
-total_score: ... // will update from cloud function
-score_count: ... // will update from cloud function
@scores
@postId_abc
-uid_1: 10
-uid_2: 20
_uid_3: 50
Whenever a user sets a score I want to use a cloud function
to add up all of the scores from the scores ref and set them to the total_score
property on that particular post. When I try the following code below I get errors:
FIREBASE WARNING: Exception was thrown by user callback. TypeError: snapshot.forEach(...).then is not a functio
and Exception from a finished function: TypeError: snapshot.forEach(...).then is not a function
It seems my snapshot.forEach((child) => { ... }).then(() => {
isn't working but the scoreCountProperty.set(...)
does increment.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.updateScore = functions.https.onCall((data, response) => {
const postId = data.postId;
const postsRef = admin.database().ref('/posts/' + postId);
const scoreCountProperty = admin.database().ref('/posts/' + postId + '/' + 'score_count');
var totalScore = 0.0;
admin.database().ref('scores').child(postId).once('value', snapshot => {
if (snapshot.exists()) {
snapshot.forEach((child) => {
totalScore += child.val()
})
.then(() => {
console.log('totalScore: ', totalScore);
return postsRef.set({ "total_score": totalScore });
})
.then(() => {
return scoreCountProperty.set(admin.database.ServerValue.increment(1));
})
.catch((error) => {
console.log('ERROR - updateScore Failed: ', error);
});
});
});