AngularFire - Get key parent orderbykey child

This is the Firebase structure that I made:

firebase structure

I just want to get key of the company where user has child uid of the user. My syntax looks like this:

self.companyid = $firebaseArray(firebase.database().ref('company').orderByChild('user/' + self.user_id.uid)); 
    self.companyid.$loaded(function() {
        console.log(self.companyid);
        loadProject();

    });

But when I do console.log(self.companyid), it produces all object of the company.

Upvotes: 0

Views: 513

Answers (1)

MurrayR
MurrayR

Reputation: 426

The $firebaseArray() function is going to return an array of Firebase objects. Based on the supplied .ref('company'), the array will contain all your company objects regardless of user.uid. The .orderByChild() will not have any effect because it's just trying to sort on your uid which, if present in the object, will always be the same.

Based on your data structure, the way to find the company object(s) for which you're a user, you'll have to iterate over the array of company objects and the users keys within each company testing for a match to your user id.

self.companies = $firebaseArray(firebase.database().ref('company'));
self.companies.$loaded(function() {
    self.companies.forEach(function(companyObj) {
        for (let key in companyObj.users) {
            if (key === self.user_id.uid) {
                console.log(companyObj.$id);
                self.companyid = companyObj.$id;
                loadProject();
            }
        }
    });
    self.companies.$destroy();
});

This is making an assumption that the data is designed in a way that your user_id will only appear within a single company object.

Keep in mind that $firebaseArray() returns an array with a live connection to the database. Once you're finished with the array, it should be destroyed.

Upvotes: 0

Related Questions