0

我正在使用Firebase雲代碼和Firebase實時數據庫。如何在雲代碼中查詢Firebase實時數據庫

我的數據庫結構爲:

-users 
     -userid32 
     -userid4734 
      -flag=true 
     -userid722 
      -flag=false 
     -userid324 

我想查詢只有誰的場「標誌」用戶是「真」。

我目前正在做的是遍歷所有用戶並逐一檢查。但是,這是沒有效率的,因爲我們在數據庫中的大量用戶的,它需要10秒以上的功能來運行:

const functions = require('firebase-functions'); 
const admin = require("firebase-admin"); 
admin.initializeApp(functions.config().firebase); 

exports.test1 = functions.https.onRequest((request, response) => { 
    // Read Users from database 
    // 
    admin.database().ref('/users').once('value').then((snapshot) => { 
     var values = snapshot.val(), 
      current, 
      numOfRelevantUsers, 
      res = {};  // Result string 

      numOfRelevantUsers = 0; 

     // Traverse through all users to check whether the user is eligible to get discount. 
     for (val in values) 
     { 
      current = values[val]; // Assign current user to avoid values[val] calls. 

      // Do something with the user 
     } 

     ... 
}); 

有沒有更有效的方法,使這個查詢並獲得唯一的相關記錄? (而不是讓所有的人都和檢查一個接一個?)

回答

1

你會使用一個火力地堡數據庫查詢:當您需要遍歷子節點

admin.database().ref('/users') 
    .orderByChild('flag').equalTo(true) 
    .once('value').then((snapshot) => { 
    const numOfRelevantUsers = snapshot.numChildren(); 

,不治療作爲普通的JSON對象生成快照。雖然這可能會起作用,但如果您使用實際範圍對值進行訂購,它會產生意想不到的結果。而是使用內置的Snapshot.forEach()方法:

snapshot.forEach(function(userSnapshot) { 
    console.log(userSnapshot.key, userSnapshot.val()); 
} 

注意,所有這一切都是相當標準的火力地堡數據庫的使用,所以我建議在文檔中花費一些額外的時間Web SDKAdmin SDK爲兩個。