简体   繁体   English

firebase查询在第二/第三级

[英]firebase query on the second/third level

I am using Javascript with Firebase and I want to make a query on a value exist on the second or the third level, My DB is like that : 我正在使用Javascript和Firebase,我想对第二级或第三级存在的值进行查询,我的数据库是这样的:

Users :
        -KNwBd5cF6iY9dWh0eFd :
                name: "Jon Snow"
                phones:
                    phone1: "0123456789"
                    phone2: "0123456987"

And I want to make a query on the phone1 value, I am using orderByChild to query the DB for now and my code is : 我想对phone1值进行查询,我现在使用orderByChild来查询数据库,我的代码是:

var ref = firebase.database().ref("users");
ref.orderByChild("name").equalTo("Jon Snow").on("value", function(snapshot) {
    console.log(snapshot.val());
});

But I can only use it to query on the value of the first level of values but how to make another query on the second or third level. 但我只能用它来查询第一级值的值,但是如何在第二级或第三级进行另一次查询。

Without knowing the phone id and considering your current database structure this wont be possible. 在不知道电话ID并考虑到您当前的数据库结构的情况下,这是不可能的。

One workaround is to use the actual phone number as the key in /phones . 一种解决方法是使用实​​际的电话号码作为/phones的键。

{ 
  users:
    userId:
       phones:
          0123456789: true
}

Then you will be able to retrieve it with: 然后你就可以用以下方法检索它:

ref.orderByChild("phones/"+phoneNumber).equalTo(true).once("value", function(snapshot) {
    console.log(snapshot.val());
});

Working jsFiddle . 工作jsFiddle


This would be simple if you had the phoneId . 如果你有phoneId这将很简单。

ref.orderByChild("phones/phone1").equalTo("0123456789").once("value", function(snapshot) {
    console.log(snapshot.val());
});

Since you don't, it turns to be a good example of how you should not be structuring a noSQL database. 既然你没有,它就会成为你不应该如何构建noSQL数据库的一个很好的例子。

noSQL databases are very flexible and its structure will depend pretty much on your application. noSQL数据库非常灵活,其结构很大程度上取决于您的应用程序。 So keep it in mind. 所以记住它。 If, for example, searching for a phoneNumber will be critical in your application and you want to have more data inside /phones/phoneNumber/ you should consider having a new separate branch to handle this in a more dedicated manner than you are doing now. 例如,如果在您的应用程序中搜索phoneNumber是至关重要的,并且您希望在/phones/phoneNumber/包含更多数据,则应考虑使用新的单独分支以比您现在更专注的方式处理此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM