Firebase - 如何在列表查询中执行where项?

时间:2016-03-27 18:28:24

标签: javascript firebase firebase-realtime-database

给出

网址为:https://myApp.firebaseio.com

并且

数据是:

  {
    "users": {
      "u00001": {
        "name": "Andy",
        "teams": {
           "t001": true,
           "t003": true
        }
      },
      ...
    },
    "teams": {
      "t001": {
        "name": "Alpha Team"
      },
      "t002": {
        "name": "Beta Team"
      },
      "t003": {
        "name": "Gamma Team"
      },
      ...
    }
  }

Andy加入的球队是['t001','t003']

问题:

是否可以使用 ONE 查询来获取Andy加入的团队的所有名称? (查找所有团队名称,其中ID在['t001','t003']中,例如期望[“Alpha团队”,“Gamma团队”])

提前致谢。

2 个答案:

答案 0 :(得分:2)

这应该有效:

var ref = new Firebase('https://myApp.firebaseio.com');
ref.child('users/u00001/teams').on('value', function(teamKeys) {
  var teamNames = [];
  teamKeys.forEach(function(teamKey) {
    ref.child('teams').child(teamKey.key()).once('value', function(teamSnapshot) {
      teamNames.push(teamSnapshot.val().name);
      if (teamNames.length == teamKeys.numChildren()) {
        console.log('All team names loaded');
      }
    }); 
  });
})

如果您担心加载时间和往返次数,请参阅Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly

答案 1 :(得分:1)



var data = { "users": { "u00001": { "name": "Andy", "teams": { "t001": true, "t003": true } }, }, "teams": { "t001": { "name": "Alpha Team" }, "t002": { "name": "Beta Team" }, "t003": { "name": "Gamma Team" } } }

function getNames(data, user) {
    var res = [];
    var teams = [];
    Object.keys(data.users).forEach(k => {
        if (data.users[k].name == user) {
            Object.keys(data.users[k].teams).forEach(t => teams.push(t))
        }
    });
    Object.keys(data.teams).forEach(t => {
        if (teams.indexOf(t) > -1) {
            res.push(data.teams[t].name);
        }
    });
    return res;
}

document.write(JSON.stringify(getNames(data, "Andy")));