Im trying to figure what I am doing incorrectly here when I want to update just a value of my field in the firestore but instead the entire field got replaced?
also for whatever reason my date
variable seems to directly become the string date
in firestore instead of the value it holds?
Here's my code for updating the Doc:
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)
}
}
The below is a screen shot of my firestore. If I hard code '05-02-2022'
in the date
part, it becomes like what you see in the image. If I kept date
as seen in the code, it becomes the date like
part.
the date
variable holds a string and likes
is a number.
I want my function to work so that when I click on my button it will add one like to the value in the likes
part, and I am trying to figure out why I cant do that
Thanks
CodePudding user response:
If you want to use the value of date
as the field name, you can use []
notation:
await updateDoc(doc(db, 'Bulletin', `bulletin`), { [date]: {likes: likes 1}})
This will still replace the entire field for that date though. If you want to update only the likes
subfield, you can use dot notation to update fields in nested objects:
await updateDoc(doc(db, 'Bulletin', `bulletin`), { [date ".likes"]: likes 1})
Finally, Firestore actually has a build in operator for incrementing values, which prevents race conditions when multiple users are updated the likes
values at almost the same time.