牧羊人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);
...
};
添加回答
舉報
0/150
提交
取消