我想要一些有关 firebase 中数据检索的解释。我不是 NoSql 数据结构方面的专家,我脑子里缺少一些东西。这对我来说不自然。不过,我想我已经了解了这种结构中双向关系的基础知识。
这是我的数据结构:
{
// Two-way relationships between accounts & logements
"accounts" : {
"uniqueId1" : {
"nom" : 'My name 1',
"email" : 'My email 1',
"logements" : {
uniqueIdLogement1 : true,
// do I have to list relationships with images & geofire here ?
uniqueIdLogement2 : true
},
"favorites" : {
uniqueIdLogement2 : true,
uniqueIdLogement25 : true,
uniqueIdLogement32 : true
}
},
....
},
// Each logement has his own "images" & "geofire" data
"logements" : {
"uniqueIdLogement1" : {
"nom_du_logement" : 'My logement name 1',
"accounts" : {
uniqueId1 : true
},
"images" : {
uniqueIdImages1 : true,
uniqueIdImages2 : true,
uniqueIdImages3 : true,
},
"geofire" : {
uniqueIdGeofire1 : true
},
},
...
},
"images" : {
"uniqueIdImages1" : {
"image" : 'My image URL 1',
"logements" : {
uniqueIdLogement1 : true
}
},
...
},
"geofire" : {
"uniqueIdGeofire1" : {
"g" : 'My geofire Data,
"l" : {
0 : '-44.34',
1 : '-3.2'
},
"logements" : {
uniqueIdLogement1 : true
}
},
...
}
}
我认为每个人对数据结构都有自己的观点,但在我看来(引用 Firebase 文档)它必须是这样的。但如果您看到一些更新,请不要犹豫!
所以,在 angularJs 中,我想列出帐户的每个“logements”,例如“uniqueId1”,并显示他们自己的“图像”和 geofire 数据(并检查它们是否是我用户最喜欢的 logements)。
可以这样做吗?
// list every logements for account ID1
// for each logement take images data & geofire data & check if favorites
// push infos in $scope.items & display with ng-repeat
与此相关的另一个问题:当我删除用户 ID1 的“logements”时,我还想删除所有图像和 geofire 引用......!也可以这样做吗?
// remove uniqueIdLogement1 from account ID 1
// remove images where "logements" = uniqueIdLogement1
// remove goofier where "logements" = uniqueIdLogement1
我想如果我理解正确的话,那对我来说就没问题了!我现在还不知道它是如何工作的,这很令人沮丧,因为我知道这种数据库有很大的潜力。您能给我解释一下一些细节吗?非常感谢
最佳答案
对于任何数据库,您通常需要连接来自多个位置的数据来构建 View 。
在关系数据库中,您可以使用 JOIN
子句,通过单个语句从这些多个位置(在本例中为表)获取数据。
在 Firebase(以及许多其他 NoSQL 数据库)中,没有内置方法可以连接来自多个位置的数据。因此,您必须在代码中执行此操作。
var ref = firebase.database().ref();
var accountRef = ref.child('accounts/uniqueId1');
accountRef.on('value', function(accountSnapshot) {
var logementCount = accountSnapshot.child('logements').numChildren;
var logementLoadedCount = 0;
accountSnapshot.child('logements').forEach(function(logementKey) {
var logementRef = ref.child('logements').child(logementKey.key);
logementRef.once('value', function(logementSnapshot) {
var logement = logementSnapshot.val();
logementLoadedCount = logementLoadedCount + 1;
if (logementLoadedCount == logementCount) {
console.log('We've loaded all logements');
}
});
});
});
许多具有 SQL 和传统 Web 开发背景的开发人员担心所有这些嵌套调用的性能。在 Firebase 中,不需要(对于合理数量的数据),因为 Firebase 通过单个连接管道传输请求。请参阅Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly .
总的来说,我强烈建议阅读这篇关于 NoSQL data modeling 的文章对一般主题有一个很好的介绍。
关于javascript - Firebase 双向关系/检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38682558/