Angular / Firebase: How to erase a database index entry when the value changes

118 Views Asked by At

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.

quasi structured like so:

users/  
    'uniqueId'/  
        name:'a user',  
        email:'[email protected]',  
        role:'admin'**  

then each property of the data is pushed to an index table like so:

index/
    users/
        name/
            'a user'/
              'newNameIndexId': 'uniqueId'
        email/
            '[email protected]'/
                'newEmailIndexId': 'uniqueId'
        role/
            admin/
                'newRoleIndexId': 'uniqueId'

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.

Here's the update method I'm calling:

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 && prop.length>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();

                    }
                }
            });
        });
    }

Any insight to a good way to get the old index entries removed is super helpful and appreciated. Thanks!

1

There are 1 best solutions below

1
On BEST ANSWER

Calling push (AngularFire $add) is great when you don't have a unique key yet. But in the case of users, you do have a unique key already. So you should normally use that for addressing the data/naming the node.

If you're adding a new node only to replace the previous node, you're probably doing something wrong.

How about modeling the index like this?

index/
    users/
        name/
            'a user'/
                'uniqueId': true
        email/
            '[email protected]'/
                'uniqueId': true
        role/
            admin/
                'uniqueId': true
                'uniqueId2': true

Using this last approach, you can just remove based on the uniqueId of the user, so you don't have to loop over the users with the same role/email/name.