1

I have a collection called users, it its filled with elements(users) named by their Firebase uids, ex:

users/1k239k1293k01k923

Lets suppose I need to retrieve an user (or all users) which have the atribute provider == "facebook".

Something like users/$someuser/provider == "facebook"

The problem is I don't know what user will match this atribute.

I'm using Javascript SDK (web)

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Rodolfo Paranhos
  • 793
  • 2
  • 7
  • 18
  • 2
    You should use [`orderByChild`](https://firebase.google.com/docs/reference/js/firebase.database.Query#orderByChild) and [`equalTo`](https://firebase.google.com/docs/reference/js/firebase.database.Query#equalTo) – Devid Farinelli Jul 10 '16 at 20:10
  • 1
    This [question](http://stackoverflow.com/questions/37910008/check-if-value-exists-in-firebase-db/37910159#37910159) will help you to work it out. – adolfosrs Jul 10 '16 at 20:24

1 Answers1

4

The Firebase documents are very good, I would advise to do some reading there.

JS:

// Provider
var provider = "facebook";
// Find all users with certain provider
var ref = firebase.database().ref("users");
    ref.orderByChild("provider").equalTo(provider).on("value", function(snapshot) {
    // iterate through each match
    snapshot.forEach(function(childSnapshot) {
        // key will be "ada" the first time and "alan" the second time
        var key = childSnapshot.key;
        // childData will be the actual contents of the child
        var childData = childSnapshot.val();
     });
});

This is a combination of orderByChild, equalTo and forEach. The forEach is used to iterate through each match and do whatever you want from there.

The .on("value" can be changed to .once("value, .on("child_added, etc..

theblindprophet
  • 7,767
  • 5
  • 37
  • 55