亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 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 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號