title: Angular / Firebase: How to erase a database index entry when the value changes
body: <p>I've got an app that indexes all properties when it saves an object. For example when a new user is created, the data (name, email, role) is pushed to a user table. </p>
  
  <p>quasi structured like so:  </p>
  
  <pre><code>users/  
      'uniqueId'/  
          name:'a user',  
          email:'user@mail.com',  
          role:'admin'**  
  </code></pre>
  
  <p>then each property of the data is pushed to an index table like so:</p>
  
  <pre><code>index/
      users/
          name/
              'a user'/
                'newNameIndexId': 'uniqueId'
          email/
              'user@mail.com'/
                  'newEmailIndexId': 'uniqueId'
          role/
              admin/
                  'newRoleIndexId': 'uniqueId'
  </code></pre>
  
  <p>The problem I have is when I update the main user fields, a new index entry is created properly but I'm not figuring out how to delete the old index entry.</p>
  
  <p>Here's the update method I'm calling:</p>
  
  <pre><code>function update(type, id, changedObject, originalObject){
          var updateRef = dataRef.child(type);
          updateRef = updateRef.child(id);
          var uploadIndexRef = dataRef.child('index/'+type);
          var updateObject = $firebaseObject(updateRef);
          updateObject.$value = changedObject;
          updateObject.$save().then(function(ref) {
              var id = ref.key();
              angular.forEach(changedObject, function(prop, key){
                  if(prop &amp;&amp; prop.length&gt;2){
                      var cleanProp = prop.toLowerCase().replace(/'+/g, '').replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "-").replace(/^-+|-+$/g, '');
                      uploadIndexRef.child(key+'/'+cleanProp).push(id);
                      if(prop !== originalObject[key]){
                          var removeOldIndex = uploadIndexRef.child(key+'/'+oIndex[key]);
                          var removeObject = $firebaseObject(removeOldIndex);
                          removeObject.$remove();
  
                      }
                  }
              });
          });
      }
  </code></pre>
  
  <p>Any insight to a good way to get the old index entries removed is super helpful and appreciated. Thanks!</p>