Angular / Firebase:如何在值更改时擦除数据库索引条目

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

我有一个应用程序可以在保存对象时为所有属性编制索引。例如,当创建新用户时,数据(姓名、电子邮件、角色)被推送给用户 table。

准结构如下:

users/  
    'uniqueId'/  
        name:'a user',  
        email:'user@mail.com',  
        role:'admin'**  

然后每个 属性 数据被推送到一个索引 table 像这样:

index/
    users/
        name/
            'a user'/
              'newNameIndexId': 'uniqueId'
        email/
            'user@mail.com'/
                'newEmailIndexId': 'uniqueId'
        role/
            admin/
                'newRoleIndexId': 'uniqueId'

我遇到的问题是,当我更新主要用户字段时,正确创建了一个新的索引条目,但我不知道如何删除旧的索引条目。

这是我调用的更新方法:

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();

                    }
                }
            });
        });
    }

对删除旧索引条目的好方法的任何见解都非常有帮助和赞赏。谢谢!

调用 push (AngularFire $add) 在您还没有唯一密钥时非常有用。但对于用户而言,您确实已经拥有唯一的密钥。所以你通常应该使用它来寻址 data/naming 节点。

如果您添加新节点只是为了替换之前的节点,那么您可能做错了什么。

像这样对索引建模怎么样?

index/
    users/
        name/
            'a user'/
                'uniqueId': true
        email/
            'user@mail.com'/
                'uniqueId': true
        role/
            admin/
                'uniqueId': true
                'uniqueId2': true

使用最后一种方法,您可以只根据用户的 uniqueId 删除,因此您不必遍历具有相同 role/email/name 的用户。