以下是我的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

缩小和映射功能是否可以解决该错误?抱歉,这个问题很傻,但是我是Firebase的新手。

最佳答案

loadedPlayers现在的状态,它是一个Query对象,因为这是orderByChild()返回的内容。您实际上并没有执行查询来获取Player/playerweek8处的数据。

您需要在loadedPlayers上使用once()方法,以实际进行查询并获取数据。

如果您不熟悉Cloud Functions,建议您执行codelab并查看sample code以了解其工作原理。

09-07 17:46