我正在尝试在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 :(得分:3)
要获取属于product2的所有类别,您应该使用:
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
});
}):