Abbadiah
Abbadiah

Reputation: 171

Finding an object by it's unique id in Firebase

I have a question. Firebase seems to generate unique id's for objects created with the push() method. While that's amazing, the official tutorial seems to omit such a simple question as to how to retrieve such an object based on it's unique id.

{
  "contacts" : {
    "-KD3p6kdEUbg38X7Osfm" : {
    "address" : "Whitley rd 22, Northampton",
    "email" : "somethingsatsomething@soso",
    "name" : "George Booney",
    "notes" : "Sounds like a serious businessman",
    "phone" : "01239485764",
    "website" : "http://www.workingatthepumps.com"
 },
   "-KD3pzA_P3pK0TCzg4zw" : {
    "address" : "Common Avenue 22, Birmingham",
    "email" : "[email protected]",
    "name" : "John Doe",
    "notes" : "Sounds like a serious businessman",
    "phone" : "44582314864",
    "website" : "http://www.wearelost.com"
}
}
}

The code to invoke it looks like this:

var ref = new Firebase("https://contactsmgr.firebaseIO.com/contacts");

        return {
            get: function() {
             return ref;   
            },
            find: function() {
            // the required code to refer to the unique id
            }
        };

Is there a simple way to do this, or is the JSON structure that I have created inherently wrong?

Upvotes: 3

Views: 2750

Answers (1)

KN_
KN_

Reputation: 356

If you have the key, you can access like this ref.child(id).

As @FrankvanPuffelen clarified, you then bind that to your AngularJS scope with:

$scope.contact = $firebaseObject(ref.child('-KD3pzA_P3pK0TCzg4zw')); 

If you do not have the key yet, and you need to look by name or email then you can use orderBy and startAt and endAt:

ref.orderByChild('phone').startAt('01239485764').endAt('01239485764');

Upvotes: 4

Related Questions