[英]How to query firebase realtime database in cloud code
我正在使用Firebase雲代碼和Firebase實時數據庫。
我的數據庫結構是:
-users
-userid32
-userid4734
-flag=true
-userid722
-flag=false
-userid324
我只想查詢字段'flag'為'true'的用戶。
我目前正在做的事情是遍歷所有用戶並逐一檢查。 但這效率不高,因為數據庫中有很多用戶,並且該函數運行需要十多秒鍾的時間:
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
}
...
});
有沒有更有效的方法來進行此查詢並僅獲取相關記錄? (而不是全部獲取並一一檢查嗎?)
您將為此使用Firebase數據庫查詢:
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());
}
請注意,所有這些都是Firebase數據庫的標准用法,因此我建議在Web SDK和Admin SDK的文檔中花一些額外的時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.