John
John

Reputation: 480

Like button, add and subtract on database. nodejs, mongodb, mongoose, jquery

I am building a website that user can like, the like button is working, it is storing the likes on the database. My question is, how can i make the user that when they click the like button again, it will subtract on the database. I have an animation of like button, 1st default state is it is grey, then when the user click it, it will turn to blue and a "liked" text will appear besides it. then when the user clicks again, it will go back to black.

Here's my code on POST route (because i am adding data to database)

app.post("/index/:id", function(req,res){
    TestData.findById(req.params.id, function(err, theUser){
        if(err){
            console.log(err);
        } else {
            theUser.likes += 1;
            theUser.save();
            console.log(theUser.likes);
        }
    });
});

my EJS file:

      <a class="likeicon" href="/index/<%= newUsers._id %>?_method=POST">
       <i class="fa fa-thumbs-o-up" aria-hidden="true" ></i>
      </a>

and my jQuery:

$(".likeicon").on('click', function(){
if($(this).css("color") === "rgb(0, 0, 255)"){
  $("#likedtxt").remove();
  $(this).css("color", "black");
  $(this).animate({fontSize: "15px"});


} else {
  $(this).css("color", "blue");
  $(this).append("<span id='likedtxt'>Liked</span>");
  $(this).animate({fontSize: "18px"});
}  
});

also another question, when i click liked, it is adding to the database, but how can i show it LIVE on the user screen that the count on likes are updated? without reloading the screen. because i dont want to use res.redirect, it refreshes the webpage.

Upvotes: 1

Views: 8070

Answers (3)

krnitheesh16
krnitheesh16

Reputation: 308

Sending values from the front-end is not a good idea...

instead, you can use MongoDB built-in operation => '$inc'

which increments the value in the field of the mongoose object model.

router.post('/:id',(req,res,next)=>{
counter = req.body.like;
TestData.update({_id:id},{$inc:{likes:counter}}).exec()
.then(result=>{
res.status(200).json({message:'liked'});
}).
catch(err=>{
res.status(500).json({error:err});
});
});

if you send req.body.likes = 1 then the value of the like field increase by 1.

if it is negative, then it will make decrement.

Upvotes: 0

BlackRockSoul
BlackRockSoul

Reputation: 66

Imo better you can write onclick function to "likeicon" button

<a class="likeicon" userId="<%= newUsers._id %>" onclink="updateLikes()">
   <i class="fa fa-thumbs-o-up" aria-hidden="true" > 49 </i>
</a>

Function:

function updateLikes() {
    id = $('.likeicon').attr('userId');
    $.post('/index/' + id, function (response) {
        $('fa-thumbs-o-up').text(response.likeCount); //your counter on a page
        //and update likes counter with response
    })
}

And node.js

app.post("/index/:id", function (req, res) {
    TestData.findById(req.params.id, function (err, theUser) {
        if (err) {
            console.log(err);
        } else {
            theUser.likes += 1;
            theUser.save();
            console.log(theUser.likes);
            res.send({likeCount: theUser.likes}); //something like this...
        }
    });
});

Upvotes: 2

SkyQ
SkyQ

Reputation: 380

For updated count likes you should send updated count of likes from server eg.:

app.post("/index/:id", function(req,res){
  TestData.findById(req.params.id, function(err, theUser){
      if(err){
          console.log(err);
          return res.status(500).send('Something went wrong!'); // You should notify user about any error    
      } else {
          theUser.likes += 1;
          theUser.save(function(err){
          if(err) return res.status(500).send('Something went wrong!');
          return res.send({likes_count: theUser.likes});
          });

      }
  });
});

Upvotes: 0

Related Questions