【发布时间】:2021-02-15 03:30:31
【问题描述】:
我的数据库布局是:
@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
每当用户设置分数时,我想使用 cloud function 将 scores 参考中的所有分数相加,并将它们设置为该特定帖子的 total_score 属性。当我尝试下面的代码时,我得到了错误:
FIREBASE WARNING: Exception was thrown by user callback. TypeError: snapshot.forEach(...).then is not a functio 和 Exception from a finished function: TypeError: snapshot.forEach(...).then is not a function
我的snapshot.forEach((child) => { ... }).then(() => { 似乎不起作用,但scoreCountProperty.set(...) 确实增加了。
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);
});
});
});
【问题讨论】:
标签: node.js firebase-realtime-database google-cloud-functions