Home > Software engineering >  How to update a specific field of data only one time for each user in firesrore in firebase v9?
How to update a specific field of data only one time for each user in firesrore in firebase v9?

Time:06-09

I am creating a sns-like web application, and trying to implement a "liking a post" function. Basically each post has data in firestore, such as the caption of the post, the image of the post, number of likes on the post and etc. What I want to do is, if a user clicks a like button on any post, the number of likes on the post clicked will be incremented by 1. However, I do not know how I can restricting each user can like only one time on each post. My current code works for incrementing the number of likes but the user can like a post as many times as the user clicks. I am totally a beginner in firebase, react and javascript and would be really appreciated for any help. Thank you.

here is my code working for incrementing a number of likes.

 const likeHandle = async () => {
        const docRef = doc(db, "posts", postId);

        await updateDoc(docRef, {
            noLikes: noLikes   1
        });
    }

CodePudding user response:

You won't be able to do this at scale inside the same document where you are tracking the number of likes, because there is a max size to each document.

What you will have to do instead is store a record of each pair of user and like in its own document in a separate collection, and check to make sure that any new like requests are not already represented in that other collection. Your UI should also probably disable likes if there is a record for that pair of user and post so that the user is not presented with an option that you don't want them to take.

CodePudding user response:

There is no direct way to limit how often a user can write a specific piece of data.

What you can do however is:

  • Add a usersWhoVoted field with UIDs to the document, or a userWhoVoted subcollection under it.
  • Write both the increased number of likes and the UID to the database in one operation (using a transaction/batched write if you chose a subcollection).
  • Use security rules that only allow the user to increment the count if they also added their UID in that operation, and only decrease the count if they removed it (if that is also a use-case you want to support).

You should probably also use the atomic increment operation, to prevent depending on client-side state that can be outdated (although your security rules should catch and reject that situation anyway).

  • Related