我写了这个firebase函数,它在添加数据时触发,它汇总子值并更新总值字段。
export const updateTotalAnswersCounts = functions.database
.ref('/CurrentGame/answers/{aid}').onWrite((change, context) => {
var collectionRef = change.after.ref.parent;
let total = 0;
collectionRef.once('value',(snapshot)=>{
console.log('snapshot',snapshot.val())
snapshot.forEach((childSnapshot)=>{
if(childSnapshot.val()!=null){
console.log('childSnapshot',childSnapshot.val())
total+=Number(childSnapshot.val())
}
return false;
})
const updates = {}
updates['/totalAnswersCount'] = total;
firebase.ref('/CurrentGame').update(updates)
})
return true;
});
当我向'答案'添加新值时,功能触发器有效。节点然后它取所有数字(在这张照片1 + 2 + 11)然后它将totalAnswersCount更新为sum = 14.
此添加操作
addAnswer() {
let answer = 3;
let userInfo = {
uid: this.uid,
gid: '1',
qid: '2',
aid: '3'
}
const answer_ref = firebase.database().ref(`CurrentGame/answers/${answer}`);
const users_answers_ref = firebase.database().ref(`GameQuestionStats/${this.user.uid}/${userInfo.qid}`);
// Return the promise from countRef.transaction() so our function
// waits for this async event to complete before it exits.
return answer_ref.transaction((current) => {
return (current || 0) + 1;
}).then(() => {
return users_answers_ref.set(userInfo,{merge:true})
});
}
此firebase功能交替工作
答案 0 :(得分:1)
原因是你必须链接Promises(因此在每个链接步骤都返回一个promise)。
以下内容应该有效:
export const updateTotalAnswersCounts = functions.database
.ref('/CurrentGame/answers/{aid}').onWrite((change, context) => {
const collectionRef = change.after.ref.parent;
let total = 0;
return collectionRef.once('value', (snapshot) => {
console.log('snapshot', snapshot.val())
snapshot.forEach((childSnapshot) => {
if (childSnapshot.val() != null) {
console.log('childSnapshot', childSnapshot.val())
total += Number(childSnapshot.val())
}
})
}).then(() => {
const updates = {}
updates['/totalAnswersCount'] = total
return firebase.ref('/CurrentGame').update(updates)
}).catch(error => {
console.log(error);
//Error treatment
});
});
我建议您查看Doug Stevenson关于此主题的视频:
https://www.youtube.com/watch?v=7IkUgCLr5oA&t=515s
https://www.youtube.com/watch?v=652XeeKNHSk
https://www.youtube.com/watch?v=d9GrysWH1Lc&t=4s
请注意,当您未在云函数中返回承诺时,案例nbr 2(它在3-4秒后有延迟和更新)是一种典型的行为。
答案 1 :(得分:0)
我建议的一个改变是使用更改中的值,并将总和追加到您的总答案数。
例如:total = total+(newvalue-oldvalue);
这样可以省去加载“一次”操作中所有值的麻烦,如果数据增长,这将非常昂贵。
最后,我(我怀疑)替代工作的原因可能是因为承诺,这是从“一次”操作执行的。希望这会对你有所帮助。