为了账号安全,请及时绑定邮箱和手机立即绑定

从 firebase 中的数组中删除

从 firebase 中的数组中删除

牧羊人nacy 2023-01-06 09:32:06
我目前无法从我的 firebase Firestore 中的数组中删除一个项目。我可以在本地删除它,但是当我刷新时它又出现了。我知道我应该使用实际值。这是我的相关代码,这是我的 Firestore 中的项目的样子const removeGoalHandler = async (goalId) => {    let goalToDel = {}    for(let i =0; i < courseGoals.length; i++){        if(courseGoals[i].id == goalId){            console.log(courseGoals[i])            goalToDel = courseGoals[i]        }    }    const removeGoal = await loansRef.doc(userId).update({        goals: firebase.firestore.FieldValue.arrayRemove(goalToDel)    })    setCourseGoals((currentGoals)=> {        return currentGoals.filter((goal)=> goal.id !== goalId)    })    setGoalCounter(goalCounter-1)};const addToFB = async (goalTitle, interestRate, years, paidOff,id) => {    //adding data to firebase, takes into account if doc exists already     if(id==undefined){        id = goalCounter    }    console.log('add to firebase')    const loadDoc = await loansRef.doc(userId).get()        .then((docSnapshot)=> {            if(docSnapshot.exists){                loansRef.doc(userId).onSnapshot((docu)=>{                    console.log('num2: '+ (goalCounter+id).toString())                    const updateLoansArr = loansRef.doc(userId).update({                        goals: firebase.firestore.FieldValue.arrayUnion({                            id: userId+(goalCounter+id).toString(),                            value: goalTitle,                            interest: interestRate,                            years: years,                            paidOff: paidOff                        })                    })                })            }            
查看完整描述

1 回答

?
慕姐8265434

TA贡献1813条经验 获得超2个赞

您遇到的问题是arrayRemove()使用严格相等来比较数组元素并确定要删除的元素,它不会像您在代码中所做的那样比较“ids”。不幸的是,这意味着每个对象都将被视为与其他所有对象不同(无论是不同的 id 还是相同的 id),无论它们有多相同,({} === {} //false),因此它找不到要删除的元素。arrayRemove()使用包含基本类型的数组会更好:(数字、字符串等)。


就目前而言,您最好的选择是获取现有文档,使用您的“id”逻辑删除所需的元素并将其写回。像这样:


const removeGoalHandler = async (goalId) => {

    const existingDoc = await loansRef.doc(userId).get();

    const goals = existingDoc.data().goals.filter(goal => goal.id !== goalId);

    await loansRef.doc(userId).update({ goals });

    setCourseGoals(goals);

    ...

};


查看完整回答
反对 回复 2023-01-06
  • 1 回答
  • 0 关注
  • 170 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号