firestore updateDoc 替换整个字段而不是更新?

firestore updateDoc replaces entire field instead of updating?

当我只想更新 firestore 中我的字段的值但整个字段都被替换时,我想弄清楚我在这里做错了什么?

同样出于某种原因,我的 date 变量似乎直接变成了 firestore 中的字符串 date 而不是它持有的值?

这是我更新文档的代码:

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 的屏幕截图。如果我在 date 部分硬编码 '05-02-2022',它就会变成你在图片中看到的那样。如果我保留代码中的 date,它就变成了 date like 部分。

date 变量保存一个字符串,likes 是一个数字。

我想让我的功能正常工作,这样当我点击我的按钮时,它会在 likes 部分的值中添加一个 like,我想弄清楚为什么我不能这样做

谢谢

如果要使用date的值作为字段名,可以使用[]表示法:

await updateDoc(doc(db, 'Bulletin', `bulletin`), { [date]: {likes: likes+1}})

尽管如此,这仍会替换该日期的整个字段。如果只想更新 likes 子字段,可以使用 dot notation 更新嵌套对象中的字段:

await updateDoc(doc(db, 'Bulletin', `bulletin`), { [date+".likes"]: likes+1})

最后,Firestore 实际上有一个用于 incrementing values 的内置运算符,它可以防止多个用户几乎同时更新 likes 值时出现竞争情况。