我的嵌套firebase.database查询返回:
[DEFAULT]: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
at error (/user_code/node_modules/firebase/node_modules/@firebase/app/dist/index.node.cjs.js:40:21)
at app (/user_code/node_modules/firebase/node_modules/@firebase/app/dist/index.node.cjs.js:297:13)
at Object.serviceNamespace [as database] (/user_code/node_modules/firebase/node_modules/@firebase/app/dist/index.node.cjs.js:355:47)
at exports.watchUpdates.functions.database.ref.onCreate (/user_code/index.js:18:14)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:120:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:151:20)
at /var/tmp/worker/worker.js:827:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
代码:
const functions = require('firebase-functions');
const firebase = require('firebase');
exports.watchUpdates = functions.database
.ref('/logs/{teamName}/session/logArchive/{id}')
.onCreate((snapshot, context) => {
//console.log(snapshot.val())
firebase.database()
.ref('/logs/{teamName}/session/statistic')
.once('value')
.then((statisticSnapshot) => {
console.log(statisticSnapshot.val());
if (statisticSnapshot.exists()) {
let newLog = snapshot.val();
let statistic = statisticSnapshot.val();
let totalParticipators = statistic.totalParticipation;
let averageEnergy = statistic.averageEnergy * totalParticipators;
let averageEnjoyment = statistic.averageEnjoyment * totalParticipators;
let newParticipator = totalParticipators + 1;
let newAverageEnergy = (averageEnergy + newLog.energy) / newParticipator;
let newAverageEnjoyment = (averageEnjoyment + newLog.enjoyment) / newParticipator;
let newAverage = (newAverageEnergy + newAverageEnjoyment) / 2;
let statisticTotalMembers = statistic.totalMembers;
let participationRate = (newParticipator * 100) / statisticTotalMembers;
let newStatisticObject = {
totalMembers: statisticTotalMembers,
participationRate: participationRate,
averageEnergy: newAverageEnergy,
averageEnjoyment: newAverageEnjoyment,
averageStat: newAverage,
totalParticipation: newParticipator,
};
return firebase.database()
.ref('/logs/{teamName}/session/statistic')
.set(newStatisticObject)
}
})
});
已注释掉的//console.log(snapshot.val();
可以按我的意愿工作,但是尝试更深入的操作会导致错误。
firebase.admin.database()
-无法解决该问题,对.admin的进一步尝试也无效。
$
上的否{teamName}
是有意的,不要认为那里有问题。
答案 0 :(得分:0)
通过以下方法解决了这个问题:
snapshot.ref.parent.parent.child('statistic')
.once('value')
.then((statisticSnapshot) => {
console.log(statisticSnapshot.val())
});
代替:
firebase.database()
.ref('/logs/{teamName}/session/statistic')
.once('value')
.then((statisticSnapshot) => {
console.log(statisticSnapshot.val());