如何在实时数据库中查询表中的所有对象

时间:2018-11-30 08:14:20

标签: javascript firebase firebase-realtime-database

我正在使用Firebase实时数据库,在该数据库中我想更新一个将为以下结构的值:

users: {
 -LSYJ4jx6VzTYuFlu9nw: {
    aadhaar: "111111111111"
    address: "Velandipalaym"
    agent: {
      commission: "3"
      id: "-LSUUJKXh2lvvhdnYRes"
      name: "Tester one"
    }
    fatherName: "Linga"
    gender: "Male"
    income: "65000"
 }
 -LSYJ4jx6VzTYuFlu9az: {
    aadhaar: "111111111111"
    address: "Velandipalaym"
    agent: {
      commission: "2"
      id: "-LSUUJKXh2lvvhdnYSes"
      name: "Tester one"
    }
    fatherName: "Linga"
    gender: "Male"
    income: "65000"
 }
}

在这些情况下,我想获取用户表中与ID匹配的所有代理:“-LSUUJKXh2lvvhdnYRes”。

我尝试使用以下查询,但没有得到所选的代理。

  export const getAgentById = (id) =>
  db
    .ref('users/')
    .child('agent')
    .orderByChild('id')
    .equalTo(id)
    .once('value');

如何让所有代理从用户表中计算出ID

1 个答案:

答案 0 :(得分:1)

尝试这种方式

export const getAgentById = (id) =>
db
.ref('users')
.orderByChild('agent/id')
.equalTo(id)
.once('value');

并在数据库中添加规则

    {
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
    "users": {
      ".indexOn": ["agent/id"]
    }  
  }
}