當我只想更新firestore中我的欄位的值但整個欄位被替換時,我試圖弄清楚我在這里做錯了什么?
也無論出于何種原因,我的date變數似乎直接成為datefirestore 中的字串而不是它所持有的值?
這是我更新檔案的代碼:
export async function addLikesToFeed(date, likes){
try{
// it literally updates to {'date': 'likes: 1'}
await updateDoc(doc(db, 'Bulletin', `bulletin`), { date: {likes: likes 1}})
} catch(error){
console.log('error updating Likes at addLikesToFeed: ', error.message)
}
}
下面是我的firestore的螢屏截圖。'05-02-2022'如果我在該部分中進行硬編碼date,它就會變得像您在影像中看到的那樣。如果我保持date在代碼中看到的那樣,它就成為了date like一部分。
該date變數包含一個字串并且likes是一個數字。
我希望我的功能能夠正常作業,這樣當我點擊我的按鈕時,它會為部件中的值添加一個類似的值likes,我試圖弄清楚為什么我不能這樣做
謝謝

uj5u.com熱心網友回復:
如果要使用的值date作為欄位名稱,可以使用[]表示法:
await updateDoc(doc(db, 'Bulletin', `bulletin`), { [date]: {likes: likes 1}})
不過,這仍將替換該日期的整個欄位。如果只想更新likes子欄位,可以使用點表示法來更新嵌套物件中的欄位:
await updateDoc(doc(db, 'Bulletin', `bulletin`), { [date ".likes"]: likes 1})
最后,Firestore 實際上有一個用于遞增值的內置運算子,它可以防止多個用戶likes幾乎同時更新值時出現競爭條件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466776.html
標籤:javascript 火力基地 谷歌云火库
