2016-08-15 4 views
1

firebase에 1 대 많은 데이터 구조를 만들려고합니다. 내 두 객체는 ​​다음과 같습니다.1 대 다수의 firebase 쿼리

category: 
{ 
    cat1: { 
     name: 'Category 1' 
    }, 
    cat2: { 
     name: 'Category 2' 
    } 
} 

products: 
{ 
    product1: { 
    name: 'Product 1', 
    categories: { 
     cat1: true 
    } 
    }, 
    product2: { 
    name: 'Product 2', 
    categories: { 
     cat1: true, 
     cat2: true 
    } 
    } 
} 

이제는이 데이터를 쿼리하여 정확히 모든 카테고리로 product2를 말할 수 있습니까?

var ref = new Firebase("https://<my-firebase-url>/products/product2"); 
    var catRef = new Firebase("https://<my-firebase-url>/category"); 
    ref.once('value', function(snap) { 
     var result = snap.val(); 
     Object.keys(result.categories).map(key => { 
     catRef.child(key).once('value', function(category){ 
... //add category to array etc 
     } 
     } 
    } 

이 문서는 child_added 이벤트를 사용하는 것이 좋습니다 .... 내가 필요한 데이터를 날 다시 얻을 수있는이를 시도했지만 그것은 비효율적 인 것 같습니다과 문서가 당신이 그것을 제안하는 것 방법과 일치하지 않지만 아이가 추가되었을 때뿐만 아니라 전체 목록을 원할 때 어떻게 이해할 수 있습니까? (https://www.firebase.com/docs/web/guide/structuring-data.html) :

// List the names of all Mary's groups 
var ref = new Firebase("https://docs-examples.firebaseio.com/web/org"); 
// fetch a list of Mary's groups 
ref.child("users/mchen/groups").on('child_added', function(snapshot) { 
    // for each group, fetch the name and print it 
    String groupKey = snapshot.key(); 
    ref.child("groups/" + groupKey + "/name").once('value', function(snapshot) { 
    System.out.println("Mary is a member of this group: " + snapshot.val()); 
    }); 
}); 
+0

워드 프로세서는 이제 사용되지 않습니다. 새로운 웹 사이트 firebase.google.com을 사용하면'child_added'에 관해서 새로 추가 된 자식뿐만 아니라 기존의 자식을 가져올 수 있습니다. Firebase [업그레이드 가이드] (https://firebase.google.com/support/guides/firebase-web)를보십시오. –

+1

"루프 된로드"의 효율성. 이것은 Firebase을 처음 접하는 개발자들의 일반적인 관심사입니다. 하지만 Firebase는 단일 연결 및 파이프 라인 요청을 통해 항목을로드하므로 합리적인 크기의 데이터 세트의 경우 대개 매우 빠릅니다. 자세한 설명은 http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786을 참조하십시오. . –

답변

3

이 제품 2에 속하는 모든 범주를 얻으려면, 당신은 사용해야합니다 firebase.com에

firebase.database().ref('products/product2/categories').on('child_added', snapshot => { 
    firebase.database().ref('category/'+snapshot.key).on('value', snap => { 
     console.log(snap.val().name + ' belongs to product2'); //Will print Category 1 and Category 2 
    }); 
}): 
관련 문제