简体   繁体   中英

Firebase - how to find all the match items with auto-generated ID, where values are false

Following the techniques on https://www.firebase.com/docs/web/guide/structuring-data.html

Given the url root is: https://myApp.firebaseio.com

And the data is:

  // Tracking two-way relationships between users and groups
  {
    "users": {
      "mchen": {
        "name": "Mary Chen",
        "groups": {
           "alpha": true,
           "bob": false, // <- I want this
           "charlie": true,
           "dave": false // <- I want this
        }
      },
      ...
    },
    "groups": {
      "alpha": {
        "name": "Alpha Group",
        "members": {
          "mchen": true,
          "hmadi": true
        }
      },
      ...
    }
  }

Is it possible to construct a Firebase query to find all the groups that have the value 'false' for user "mchen" (basically I want bob and dave)? How?

eg new Firebase(' https://myApp.firebaseio.com/users/mchen/groups ') ...

In my real code, alpha, bob, charlie and dave are Firebase auto-generated keys, but the same query should solve my problem. (I'm using Firebase Web version)

Thanks in advance.

Finally got it working. I'm not an expert, but I hope this helps anybody not familiar with Firebase:

If you only use Firebase:

var ref = new Firebase('https://myApp.firebaseio.com/users/mchen/groups');
ref.orderByValue().equalTo(false).on('value', function(data){
  console.log(data.val());
})

If you use AngularFire:

var ref = new Firebase('https://myApp.firebaseio.com/users/mchen/groups');
$firebaseArray(ref.orderByValue().equalTo(false)).$loaded().then(function(data){
  console.log(data);
});

Note:

  • orderByValue() is the one to use without knowing the keys
  • Use equalTo(false), not equalTo('false')
  • $firebaseArray is the one that returns multi items, not $firebaseObject

A rule is also required for performance:

{
  "rules": {
    "users": {
      "$userName": { // A better way would be using an auto-generated ID in here
        "groups": {
          ".indexOn" : ".value" // add index on the value - notice it's .value
        }
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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