gpt4 book ai didi

javascript - 一对多 firebase 查询

转载 作者:行者123 更新时间:2023-11-30 11:52:51 29 4
gpt4 key购买 nike

我正在尝试在 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());
});
});

最佳答案

要获取属于 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
});
}):

关于javascript - 一对多 firebase 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38954249/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com