简体   繁体   中英

How to ensure that a user can only click like button once for each post?

I want to add a like button.If a user clicks on like button ofa particular post the number of likes of that particular post should increase by 1.However if he clicks again on the like button of the same post the number of likes should decrease by 1.

In my code the user can give more than 1 like to each post.How to change that?

Javascript code is:

 Template.postItem.events({    
'click button':function(event){
            event.preventDefault();
            var documentId = this._id;

            this.likes=this.likes+1;
            console.log(this);
            Posts.update({ _id: documentId },{$set:{likes:this.likes}});
            }


            });

HTML code:

<template name="postItem">
    <li>
    {{_id}}
    <h4>{{name}}</h4>
    <i>Posted by {{postedBy}} on {{createdAt}}</i>
    <br>
    {{likes}}<button class="btn btn-default glyphicon glyphicon-hand-up" >Like</button>

Here {{button}} is a helper of postItem which returns the value of the number of like on each post.

You can have in the Posts document a variable "likes" as an array containing the IDs of users who like the post.

Post = {
   likes: [String]
}

And you can check if the specific user already like the post.

var Post = Posts.find({_id: documentId, likes: Meteor.userId()});

Documentation for mongo: https://docs.mongodb.com/manual/tutorial/query-documents/#match-an-array-element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM