以下是我的firebase数据库云功能的index.JS
。
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.update = functions.database.ref('/Player')
.onWrite(event=>{
ref = admin.database().ref(`/users/UMFabxncKoZ6XcHpPQYZHizJ7Yr1/week1`);
pref1 = admin.database().ref("Player").child("playerweek8");
ref2 = admin.database().ref(`/users/UMFabxncKoZ6XcHpPQYZHizJ7Yr1`);
if(n === 2){
ref2.once('value', function(usersSnapshot){
var users = usersSnapshot.val();
var selection = users.selection;
const loadedPlayers = admin.database().ref("Player").child("playerweek8").orderByChild("id");
var normalizedPlayers = loadedPlayers.reduce(function(acc, next) { acc[next.id] = next; return acc; }, {});
var selectedPlayers = selection.map(function(num){
return normalizedPlayers[num];
});
var players = selectedPlayers;
var sum = function(items, prop){
return items.reduce( function(a, b){
return a + b[prop];
}, 0);
};
var points = sum(players, 'goals');
return ref.set(points);
});
}
else return ref.set(0);
});
该函数返回错误消息:TypeError: loadedPlayers.reduce is not a function at /user_code/index
还有一种方法可以使用reduce和mapping函数来解决这个错误吗?很抱歉,如果这个问题很愚蠢,但我是Firebase新手。
答案 0 :(得分:2)
loadedPlayers
现在的方式,它是一个Query对象,因为这是orderByChild()返回的内容。您实际上没有执行查询以获取Player/playerweek8
的数据。
您需要在loadedPlayers上使用once()方法来实际进行查询并获取数据。
如果您是Cloud Functions的新手,我建议您执行codelab并查看sample code以了解其功能。