Search code examples
javascriptmongodbmeteorhandlebars.js

Mongo DB increment if statement (Meteor App)


I cannot seem to get around this seemingly simple issue.

The code below allows me to add or subtract the number of likes by 1 on my post objects.

I would like to be able to do the following:

If postLikes = 0 then stop allowing me to reduce the number of likes.

I don't want to be able to reduce number of likes past 0.

Here is my code:

Template.post.events({
  "click .likeButton": function() {
    // Set the checked property to the opposite of its current value
    Posts.update(this._id, {
      $inc: {
        postLikes: 1
      }
    });
  },
  "click .dislikeButton": function() {

    // Set the checked property to the opposite of its current value

    Posts.update(this._id, {
      $inc: {
        postLikes: -1
      }
    });
  }
});

Solution

  • Well, what about having a condition before your update?

    Update - Never mind. Better way to accomplish this is via the query!

    "click .dislikeButton": function() {
        Posts.update({_id : this._id, postLikes : {$gt : 0}}, {
          $inc: {
            postLikes: -1
          }
        });
    }