Firebase 查询双重嵌套 [英] Firebase Query Double Nested

查看:38
本文介绍了Firebase 查询双重嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于 firebase 中的以下数据结构,我想运行查询以检索博客efg".我现在不知道用户 ID.

Given the data structure below in firebase, i want to run a query to retrieve the blog 'efg'. I don't know the user id at this point.

{Users :
     "1234567": {
          name: 'Bob',
          blogs: {
               'abc':{..},
               'zyx':{..}
          }
     },
     "7654321": {
          name: 'Frank',
          blogs: {
               'efg':{..},
               'hij':{..}
          }
     }
}

推荐答案

Firebase API 只允许您过滤一级深度的子​​项(或 具有已知路径) 及其 orderByChildequalTo 方法.

The Firebase API only allows you to filter children one level deep (or with a known path) with its orderByChild and equalTo methods.

因此无需修改/扩展您当前的数据结构,只需选择检索所有数据并在客户端对其进行过滤:

So without modifying/expanding your current data structure that just leaves the option to retrieve all data and filter it client-side:

var ref = firebase.database().ref('Users');
ref.once('value', function(snapshot) {
    snapshot.forEach(function(userSnapshot) {
        var blogs = userSnapshot.val().blogs;
        var daBlog = blogs['efg'];
    });
});

这当然是非常低效的,并且当您拥有大量用户/博客时无法扩展.

This is of course highly inefficient and won't scale when you have a non-trivial number of users/blogs.

因此,常见的解决方案是对树建立所谓的索引,将您要查找的键映射到它所在的路径:

So the common solution to that is to a so-called index to your tree that maps the key that you are looking for to the path where it resides:

{Blogs:
     "abc": "1234567",
     "zyx": "1234567",
     "efg": "7654321",
     "hij": "7654321"
}

然后您可以使用以下方法快速访问博客:

Then you can quickly access the blog using:

var ref = firebase.database().ref();
ref.child('Blogs/efg').once('value', function(snapshot) {
    var user = snapshot.val();
    ref.child('Blogs/'+user+'/blogs').once('value', function(blogSnapshot) {
        var daBlog = blogSnapshot.val();
    });
});

您可能还想重新考虑是否可以重组数据以更好地适应您的用例和 Firebase 的限制.他们有一些关于构建数据的很好的文档,但对于 NoSQL/分层数据库的新手来说,最重要的文档似乎是 避免筑巢".

You might also want to reconsider if you can restructure your data to better fit your use-case and Firebase's limitations. They have some good documentation on structuring your data, but the most important one for people new to NoSQL/hierarchical databases seems to be "avoid building nests".

另请参阅我对 Firebase 查询是否是孩子的孩子的回答包含一个值 作为一个很好的例子.我还建议阅读Firebase 中的多对多关系,以及这篇关于一般 NoSQL 数据建模的文章.

Also see my answer on Firebase query if child of child contains a value for a good example. I'd also recommend reading about many-to-many relationships in Firebase, and this article on general NoSQL data modeling.

这篇关于Firebase 查询双重嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆