2017-01-26 34 views
0

我想知道如何檢查我的Firebase數據庫中是否存在特定值。正確的方法來檢查Firebase陣列中的特定值

這是我目前的佈局:

MYAPP 
    |_______________users 
    |     |_____OshwYF72Jhd9bUw56W7d 
    |     |     | 
    |     |     |__username 
    |     |     |__email    
    |     |     |__friends    
    |     |       | 
    |     |       |__KbHy4293dYgVtT9pdoW 
    |     |       |__PS8tgw53SnO892Jhweh 
    |     |       |__Qufi83bdyg037D7RBif 
    |     |       |__Gicuwy8r23ndoijdakr 
    |     | 
    |     |_____KbHy4293dYgVtT9pdoW 
    |     |_____PS8tgw53SnO892Jhweh 
    |     |_____Gicuwy8r23ndoijdakr 
    | 
    |__conversations 

我希望能夠檢查特定的ID位於users/"UserID"/friends文件夾中。

我想知道是否需要獲取friends的全部內容,然後使用Javascript遍歷返回的數組,或者是否存在Firebase方法,如果提供的ID能夠執行檢查?

這是我目前的嘗試:

function checkIfFriend(receivedFriendId){ 
    // receivedFriendId is the ID I want to check. 
    // globaluid is the currently logged in user's ID (it sits between "users" and "friends") 

    // Attempting to check for the presence of receivedFriendId 
    return firebase.database().ref('/users/' + globaluid + '/friends/').child(receivedFriendId).once('value', function(snapshot) { 

     if (snapshot.exists()) { 
      console.log("This ID exists."); 
      }else{ 
      console.log("This ID doesn't exist."); 
      }    

    }); 
} 

這使console.logging 「這個ID不存在。」即使ID在數據庫中的該位置存在。

我想知道是否可以通過在上述查詢中發送ID來檢查ID的存在,還是需要返回friends的全部內容,然後遍歷返回的列表以查看ID是否爲當下?

回答

0

這工作:

function checkIfFriend(receivedFriendId){ 

    var ref = firebase.database().ref().child('/users/'+globaluid+'/friends/'); 

     ref.on("child_added", function(child) { 

      var IDofFriends = child.val(); 

       if(IDofFriends == receivedFriendId){ 
        console.log("The other user's ID is in the currently signed in user's friend list, they are friends!"); 
       }else{ 
        console.log("This user's ID is NOT in the currently signed in user's friend list, they are NOT friends! So do nothing."); 
       } 
     }); 
} 

雖然它繼續通過它找到一個匹配的ID即使在陣列運行的問題。我不知道如何阻止它運行,我試過return;,我試過設置一個標誌,但似乎都沒有工作。

如果任何人一旦找到匹配項就可以停止迭代,請將其作爲回答發佈,我會接受它而不是我的。

+0

看看'forEach'的文檔,特別是關於取消迭代/枚舉的部分。我認爲這會有所幫助。 https://firebase.google.com/docs/reference/admin/node/admin.database.DataSnapshot#forEach – adrice727

相關問題