在字段上进行Firebase实时数据库查询

时间:2019-04-22 12:40:15

标签: javascript firebase firebase-realtime-database

我有一个具有以下员工数据结构的firebase数据库。我也有一个用户表,该表具有'companyId'属性。每次用户登录时,我都希望获取与用户“ companyId”匹配的所有员工。可以使用firebase数据库规则来实现此功能,还是我必须编写一些查询。

Employee: 
{
  "+911234567890" : {
    "admin" : true,
    "companyId" : "C1",
    "depId" : "D5",
    "designation" : "D1",
    "dob" : "2019-04-02T18:30:00.000Z",
    "doj" : "2019-04-18T18:30:00.000Z",
    "empEmail" : "nishant.k@zetwerk.com",
    "empId" : "E4",
    "empPhone" : "+911234567890",
    "first_name" : "Nishanth",
    "gender" : "male",
    "last_name" : "K",
    "manager" : "M2",
    "type" : "permanent"
  },
  "+919035105184" : {
    "admin" : true,
    "companyId" : "C2",
    "depId" : "D1",
    "designation" : "Software engineer",
    "dob" : "1991-07-31T18:30:00.000Z",
    "doj" : "2018-07-24T18:30:00.000Z",
    "empEmail" : "arpit.s@zetwerk.com",
    "empId" : "E10",
    "empPhone" : "+919035105184",
    "first_name" : "Arpit",
    "gender" : "male",
    "last_name" : "Srivastava",
    "manager" : "M1",
    "type" : "PERMANANENT"
  },
  "+919698286236" : {
    "admin" : false,
    "companyId" : "C1",
    "companyName" : "Zetwerk",
    "depId" : "D1",
    "depName" : "Engineering",
    "empEmail" : "dhanalakshmi.s@zetwerk.com",
    "empId" : "E1",
    "empPhone" : "+919698286236",
    "firebaseId" : "-LbNvaKFjqaaMl_JbNxd",
    "first_name" : "Dhanalakshmi",
    "type" : "contract"
  },
  "+919738749877" : {
    "companyId" : "C1",
    "depId" : "D2",
    "empEmail" : "sagar.k@zetwerk.com",
    "empId" : "E3",
    "empPhone" : "+919738749877",
    "firebaseId" : "-LbNbABScOEzl-sMFE1u",
    "first_name" : "Sagar",
    "type" : "permanent"
  },
  "+919972984851" : {
    "admin" : true,
    "companyId" : "C1",
    "depId" : "D6",
    "designation" : "SDE",
    "dob" : "2019-04-23T18:30:00.000Z",
    "doj" : "2019-04-02T18:30:00.000Z",
    "empEmail" : "saikumarganji1994@gmail.com",
    "empId" : "Z002",
    "empPhone" : "+919972984851",
    "first_name" : "Sai",
    "gender" : "male",
    "last_name" : "Kumar",
    "type" : "permanent"
  }
}


User:
 "1":{
  "Name" : "Nishant Gupta",
  "companyId" : "C1",
  "role" : "admin"
} 

1 个答案:

答案 0 :(得分:2)

您确实必须使用查询,如下所示。我假设您在前端知道用户的companyId;

  var db = firebase.database();

  var userCompanyId = 'C1';  //you'll probably get this value from the user profile

  db.ref('Employee')
    .orderByChild('companyId')
    .equalTo(userCompanyId)   
    .once('value', function(dataSnapshot) {
      dataSnapshot.forEach(function(childSnapshot) {
        var childKey = childSnapshot.key;
        var childData = childSnapshot.val();
        console.log('childKey : ', childKey);
        console.log('childData : ', childData);
      });
    });

在此处查看文档:{​​{3}}

相关问题