[英]How to Structure Firebase Realtime DB read request: Order by Key's Child
I have data stored in a firebase realtime database, in the following format. 我将数据以以下格式存储在Firebase实时数据库中。
users:
-L5ZAb7r10_nqss7Ag:
role: "user"
email: "person@example.com"
username: "King Arthur"
-KL3Abnar7_nals8:
role: "admin"
email: "other@example.com"
username: "Queen Ferdinand"
And in the database.rules.json
I have: 在
database.rules.json
我有:
"users":{
".indexOn":["email"],
".write": false,
".read": "auth != null"
},
On the front end I have a user giving their email, having been authenticated with Google OAuth, and I want to see if their email is a valid user, and if so return their role and username, otherwise throw an error. 在前端,我有一个用户已通过Google OAuth进行了身份验证,并提供了他们的电子邮件,我想查看他们的电子邮件是否为有效用户,如果是,请返回其角色和用户名,否则将引发错误。 Right now I loop through the 'n' accounts and check each account's email.
现在,我循环浏览“ n”个帐户并检查每个帐户的电子邮件。 O(n) is obviously a really sucky runtime.
O(n)显然是一个很烂的运行时。
Not knowing what the user's key in the database is (the "-L5ZAb7r10_nqss7Ag" part), I want to be able to check for the given email in O(1) by searching the email in the indexed database. 不知道数据库中用户的密钥是什么(“ -L5ZAb7r10_nqss7Ag”部分),我希望能够通过在索引数据库中搜索电子邮件来检查O(1)中的给定电子邮件。 What I have in mind is something like the below.
我想到的是类似下面的内容。 If this is posisble can someone point me to the riht documentation for the correct syntax?
如果这是可疑的,有人可以指出我的正确文档以获取正确的语法吗?
firebase.database().ref(`/users/`).getIndexedValue($key/person@example.com).once('value').then(function(snap){
if(snap == null) console.log("error);
else{
user = snap.val();
console.log(user[role]);
console.log(user[username]);
}
}
I know the above won't work, .getIndexedValue()
isn't real. 我知道上述方法不起作用,
.getIndexedValue()
不是真实的。 What would be the correct syntax for this functionality? 此功能的正确语法是什么? Is there someway to look for a specific indexed value (the email) that sits below an arbitrary partent (the
-KL3Abnar7_nals8
)? 是否有某种方法可以查找位于任意
-KL3Abnar7_nals8
( -KL3Abnar7_nals8
)下面的特定索引值(电子邮件)?
You're looking for orderByChild()
and equalTo()
. 您正在寻找
orderByChild()
和equalTo()
。 Something like this: 像这样:
firebase.database()
.ref('users')
.orderByChild('email')
.equalTo('person@example.com')
.once('value').then(function(snapshot){
if (snapshot.exists()) {
snapshot.forEach(function(snap) {
user = snap.val();
console.log(user[role]);
console.log(user[username]);
})
}
}
To learn more about Firebase Database queries, see the documentation on sorting and filtering data . 要了解有关Firebase数据库查询的更多信息,请参阅有关数据排序和过滤的文档 。 I'd also recommend checking some previous questions on the topic .
我还建议您查看有关该主题的先前问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.