2016-05-05 52 views
2

所有指定項目獲取數據我有這樣的結構:從火力地堡包含在「陣」

users 
- user1 
    - name: 'Bob' 
    - age: 25 
    - posts 
     - bobPost1 
      - text: 'Lorem ipsum...' 
      - tags 
      - web: true 
      - programming: true 
      - school: true 
     - bobPost2 
      - text: 'Lorem ipsum dolor...' 
      - tags 
      - web: true 
      - design: true 
      - school: true 
     - bobPost3 
      - text: 'Sample text...' 
      - tags 
      - web: true 
      - programming: true 

我想通過標籤來檢索所有Bob的帖子。例如「網絡」和「學校」。結果應該通過post1和post2。 是否可以通過firebase實現此目標,還是應該獲取所有帖子然後過濾它們?

回答

1

無論如何,您都必須獲得整個post的數據快照,但幸運的是,這並不是很多需要擔心的數據。

var ref = new Firebase("https://docs-examples.firebaseio.com/users/user1/posts"); 
ref.once("value", function(snapshot) { 
    // Gets everything under "posts", iterates each post 
    snapshot.forEach(function(childSnapshot) { 
     // "bobpost1", "bobpost2", etc 
     var key = childSnapshot.key(); 
     // Data underneath bobpost# 
     var childData = childSnapshot.val(); 

     // Iterates through tags 
     for(i in childData.tags) { 
      // Do/check something 
      // If post contains all specified tags, then store key somewhere 
     } 
    }); 
}); 

您可以通過使用forEach所有迭代後,然後保存裏面key後的名稱和內部childData數據。

childData看起來像:

- text: 'Lorem ipsum dolor...' 
- tags 
    - web: true 
    - design: true 
    - school: true 

然後通過tags爲每個循環做一些檢查常規的JavaScript迭代。我建議如果所有的標籤被找到或者正在檢查的東西都存儲在一個數組中的key

請記住,Firebase調用是異步的,並且在調用.once之後數據不會始終準備就緒。執行回撥中的所有操作。

Firebase | forEach