Creating a like button with collection update


#1

I’m creating a like button for my app.

Basically, when the “like-button” class is clicked, I want the {{likenum}} field to increase by 1.

I’m trying to achieve this by updating the respective collection.

Below is the code I’m using which is still not working;

                 'click .like-button'() {
                 var likenum ++;
                 Positivecomments.update(this._id, {
                 $set: { likenum: likenum },
                 });
                 }

The code above is giving me errors. Can anyone help me fix it?

Also, it would be great if you can also help me prevent one user from liking a post more than once.

Thanks.


#2

Have you checked Atmosphere for packages to help you accomplish this?.. I have a whole array of packages written under the Socialize namespace that help to implement social features into meteor apps. Specifically the Likeable packages helps to create models that can be liked and seems to be exactly what you are looking for.


#3

this.likenum=this.likenum+1;
Positivecomments.update(this._id, {
$set: { likenum: likenum },
});

When you are inserting comment in mongo databse give each comment a ‘likenum’ field and set it to 0.
And then use the above code in click event.


#4

This is all well and good, but what happens when you want to know if the current user already liked it and then restrict them from liking it again?


#5

@harshitbisht99 thanks. you are awesome.


#6

you can create a Combination mongo database which can store a key combination.
Say
MeteoruserId()+’ '+this.Id
Once a user clicks on like button the first time the key gets stored in the combination databse and the number of likes increase by 1.
But when the user tries to click the like button again you can check for the combination in the database.The code can be–

AnswerLikes=new Mongo.Collection(‘answerlikes’);

‘click button’:function(event){
event.preventDefault();
var documentId = this._id;
var currentUser=Meteor.userId();
var clickCombination=documentId+’ '+Meteor.userId();

        if (AnswerLikes.findOne({combination:clickCombination})== undefined)
        {
        AnswerLikes.insert({
            combination:clickCombination
        });
        this.likes=this.likes+1;
        
        Positivecomments.update({ _id: documentId },{$set:{likes:this.likes}});

You can also use an else statement to decrease the like by 1 if that particular use click the like button second time.
Hope it helps


#7

wow, I can’t even… :sob:


#8

hello @copleykj can you please show me some demos of socialize. i know it is really good, but i have no idea how to implement it. Thanks.


#9

Here is an explanation on another recent post. Let me know if it is helpful.


#10

I did Socialize-starter that applies the socialize packages. Needs some updating, but it works: https://github.com/StorytellerCZ/Socialize-starter