Search code examples
firebaseangularfirefirebasesimplelogindenormalized

Fetching denormalized data with firebase, angularFire


I'm trying to fetch all flowers data which belongs to a certain user, in this case simplelogin:69.

I'm starting with fetching all flower keys from the user, like this:

/users/simplelogin:69/flowers/

var ref = new Firebase("https://URL.firebaseio.com/users/"+uid+"/flowers");
var sync = $firebase(ref);

Now im stuck figuring out a clean way to fetch all the flower data by looping thrue every flower key from simplelogin:69 without looping thrue EVERY key in /flowers/ (in example below i only have three flower keys but in production i might have 10k).

I tried FirebaseIndex and firebase-util, but can't get it to work properly. Do anyone have any tips or anything? I've read previous posts here on stack but most seems out of date or not really suited for what im going for. Would really appriciate anything that can be solved with AngularFire.

Kind regards, Elias

{
  "flowers" : {
    "-JiU57sFAfQwYtIq-LCl" : {
      "image" : "test",
      "name" : "test",
      "type" : "Roses",
      "uid" : "simplelogin:69"
    },
    "-JiU9-3ajlnFLpyUmBvL" : {
      "image" : "dasdasd",
      "name" : "sadasdas",
      "type" : "Roses",
      "uid" : "simplelogin:69"
    },
    "-JiUF-mioK3jQCYy6ZiG" : {
      "image" : "ss",
      "name" : "ss",
      "type" : "Lilies",
      "uid" : "simplelogin:69"
    }
  },
  "users" : {
    "simplelogin:69" : {
      "flowers" : {
        "-JiU57sFAfQwYtIq-LCl" : true,
        "-JiU9-3ajlnFLpyUmBvL" : true,
        "-JiUF-mioK3jQCYy6ZiG" : true
      }
    },
    "simplelogin:70" : {

    },
    "simplelogin:71" : {

    }
  }
}

Solution

  • Got it to work now, thanks to @Kato 's answer on thread: Firebase data normalized. How should I fetch a collection based on this structure? (tried it before creating this thread but didnt get it to work, so made som small changes and now it works).

    Posting the solution for anyone stubling upon the same situation:

    $scope.flowers = {};
    
    var flowerRef = new Firebase('https://URL.firebaseio.com/flowers/');
    var keyRef = new Firebase('https://URL.firebaseio.com/users/'+checkAuth.auth.uid+'/flowers');
    
    keyRef.on('child_added', function(snap) {
        var flowerId = snap.key();
        flowerRef.child(flowerId).on('value', function(snap) {
            $timeout(function() {
               if( snap.val() === null ) {
                  delete $scope.flowers[flowerId];
               }
               else {
                  $scope.flowers[flowerId] = snap.val();
               }
            });
        });
    });
    
    keyRef.on('child_removed', function(snap) {
        var flowerId = snap.key();
        $timeout(function(snap) {
            delete $scope.flowers[flowerId];
        });
    });