我尝试在此 Firestore 事务中删除一个值并设置一个值但不起作用

I try to remove a value and set a value in this Firestore Transaction but not working

我尝试从数组中删除一个值,但只能找到这样的示例,其中首先获取值的 index,然后使用 splice.[=18 删除该值=]

我没有索引,数组就是这样:

我必须删除 ANONYMOUS 并添加 NON_ANONYMOUS

const userRef = firebase.db.collection('users').doc(userId);

    firebase.db
        .runTransaction(transaction => {
            // This code may get re-run multiple times if there are conflicts.
            return transaction.get(userRef).then(doc => {
                if (!doc.exists) {
                    console.log('Transaction failed: User dont exist!');
                    return;
                }

                const newRoles = doc.data().roles;
                newRoles.push(ROLES.NON_ANON);
                // HERE I MUST REMOVE THE ROLE ANONYMOUS 
                transaction.update(userRef, { roles: newRoles });
            });
        })
        .then(function (newRoles) {
            console.log(`Transaction successfully committed! ${newRoles}`);
        })
        .catch(function (error) {
            console.log('Transaction failed: ', error);
        });

我试过这样

const newRoles= newRoles.splice(newRoles .indexOf('anonymouse'), 1);

但它不起作用。我做错了什么?

JavaScript 中的字符串区分大小写。您的代码正在寻找“anonymouse”,但该数组包含“ANONYMOUS”。您必须传递要删除的确切字符串。我建议在更新之前记录数组的最终值,以确保您确实删除了它。