簡體   English   中英

如何使用雲函數對 Firebase 實時數據庫、Node.js 和 Javascript 進行排序和過濾以獲得“高分”排行榜

[英]How to Sort and Filter Firebase Realtime Database with Cloud Functions, Node.js & Javascript for 'High Score' Leaderboard

幾天來我一直在研究和試錯,但沒有任何工作。 在測試中,我在我的 Firebase 實時數據庫中創建了一些測試節點,以嘗試計算函數的邏輯。 我的文件樹如下所示:

在此處輸入圖像描述

為了簡單地讓基礎工作正常,我在TestUsers節點下創建了幾個用戶,每個用戶都有一個非常簡單的Statistics子結構,然后是一個orbs值。

我正在嘗試做的事情:

在更新任何用戶下的orbs值后,我想編寫(嗯,技術上“更新”) Output/firstPlace子項,以包括前 3 名用戶(具有最高 orb 計數的用戶名和球體數量) TestUsers下的所有用戶。

看起來超級簡單,相信我,我知道有大量關於排序和過濾 Firebase 實時數據庫數據的文檔,但是從閱讀本文檔的幾天來看,我一直無法將它們拼湊在一起。

我正在使用 VS Code 編寫我的函數並將它們部署到我的 Firebase 項目中。

我寫的 function 嘗試執行上述操作是這樣的:

//Define a new function with a base path and set it to run when a child of this path is changed
exports.testTopPlayers1 = functions.database.ref('/TestUsers/{user}/Statistics').onUpdate(_ => { 

    var allPlayersRef = admin.database().ref('/TestUsers/{user}'); //When this function runs, assign a new path of all users

        //Get a snapshot of the top 3 users with the highest orb count
        allPlayersRef.orderByChild('orbs').limitToLast(3).once('value', (snap) => { 

          //For each child from the above snap (should be 3)...
          snap.forEach((child, context) => {

                const username = context.params.user; //Assign the username to a const
                const afterOrbAmount = child.after.val();
                const orbAmount = afterOrbAmount.orbs; //Assign the number of orbs to a const

                //Return (Promise?) by updating the data in '/Output/firstPlace' with the username and orb amount.
                return admin.database().ref('/Output/firstPlace').update({[username]: [orbAmount]});
          });
  })
})

我希望使用.forEach ,它應該運行寫入'/Output/firstPlace部分 3 次,有效地給我 3 個新的鍵值對。 但什么也沒有發生。

根據我正在嘗試做的事情,您能否更正我的代碼或向我展示在后端實現這樣的高分排序的正確方法?

您不會從代碼的頂層返回任何內容,這意味着 Cloud Functions 無法知道您的代碼何時完成。 因此:它在最后一個}之后停止您的代碼,這是在數據庫讀取完成之前。

您的代碼應如下所示:

exports.testTopPlayers1 = functions.database.ref('/TestUsers/{user}/Statistics').onUpdate(_ => { 

    var allPlayersRef = admin.database().ref('/TestUsers/{user}'); //When this function runs, assign a new path of all users

    let query = allPlayersRef.orderByChild('orbs').limitToLast(3)
    return query.once('value').then((snap) => { 
        let promises = [];
        snap.forEach((child, context) => {
            const username = context.params.user;
            const afterOrbAmount = child.after.val();
            const orbAmount = afterOrbAmount.orbs;

            promises.push(admin.database().ref('/Output/firstPlace').update({[username]: [orbAmount]}));

        });
        return Promise.all(promises);
    })
})

您的代碼中可能存在更多問題,但這可確保您的 Cloud Function 將繼續運行,直到查詢和后續更新完成。

我強烈建議您學習以下內容,以了解有關如何控制 Cloud Function 何時終止的更多信息:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM