Increasing a value in Mongo DB with a conditional statement in a Meteor application

This seemingly simple issue has been causing me some trouble.

With the code provided below, I am able to increase or decrease the number of likes on my posts by 1.

I am looking to achieve the following:

If postLikes = 0, then prevent further reduction of likes

It should not be possible to bring the number of likes below 0.

Below is the code snippet in question:

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
      }
    });
  }
});

Answer №1

How about considering a condition before proceeding with the update?

Update - Scratch that. A more effective way to achieve this is by using a query!

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

Answer №2

Only apply your modifier if a document meets the criteria specified in the first argument of the `update' function, which is the selector. It's best to optimize and use just one database call, letting the database handle object criteria whenever possible. Here's an example:

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

For more information, refer to the Mongo update documentation and the Meteor's update guide.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the purpose of deserializing the user for every request using PassportJS?

While I have scoured the official documentation and various online resources, I am still unable to find a solution to what seems like an obvious question. When working with Passport.js, it is necessary to define two methods - one for serializing and one f ...

Shortcut to prevent false 0 values

When my server responds, it sends back an object structured as follows: { success: integer } Meanwhile, on the client side I'm using: return body && body.success; The issue arises when the integer is zero, causing the above code to return ...

Utilizing the fs module in Node.js

Hello friends! Currently I am faced with an issue while trying to import the fs module in nodejs. Initially, I utilized require to import it like so: const fs = require('fs'); Everything was functioning smoothly until recently when it suddenly ...

Ways to prevent the loading of images during webpage loading

I have encountered an issue with my eCommerce site developed using Laravel 7. Whenever I click on the category page, all product images are being loaded, causing high bandwidth usage. The category "Appereal" contains over 100 products, and although I imple ...

Is there a way to make an HTML link target the same as JavaScript window.opener?

Within my project, the main page is where users log in and access the primary tables. Additionally, there are numerous supplementary pages that open in separate windows. Once the login session times out, it is essential to restrict user access to any cont ...

Styling Images with Gradient using CSS

Looking to create a unique effect on an image by adding a radial gradient that seamlessly fades into the background color. Despite my efforts, I haven't been able to achieve this using filters and my current code is a bit messy. Here's what I ha ...

The Quasar application does not eliminate console.log() statements during production builds

I've been facing difficulties in removing the console.log() from my Quasar app for production builds. Despite checking solutions on various platforms like StackOverflow, Quasar forums, and GitHub, I am still struggling to eliminate the console.log st ...

Attempting to remove options in a Multiple Choice scenario by selecting the X icon beside each one

I'm working on a multiple choice quiz and I'd like to add a button or icon resembling X in front of each option (even in front of the radio button), so that when I click on it, only that specific option is deleted. How can I achieve this? For in ...

The VueJS component failed to import successfully

Trying a simple demo to explore VueJS components, but encountering an error when loading the page: Unexpected Token Import in this line import GISView from './components/GISView.vue'; If I remove this line, GISView is not defined. Using Laravel ...

Is it possible to nest a React component within a state?

Is it permissible to use any of the three options below, but I can't find recent official information regarding this? constructor(props) { this.state = { item: <SomeItem />, item1: () => <SomeItem />, item2: Some ...

issue with data binding in ons-dialog

Utilizing an ons-dialog to display a popup prompting the user to sign up for a newsletter. I have set a 3-second timeout to prevent users from immediately closing the prompt without reading it or waiting. I aim to initially show the dialog with the ' ...

How can I compare the ID values across both arrays within the object?

I am trying to find a way to match the id from two arrays using an OR condition. For example: { stauts:"matched", members:{ groupA:[{ "userName" : "Malik", "firstName" : "Adil", "_id&q ...

Ways to set the base URL on the development server for a call to react-scripts start

I am facing an issue with configuring my primary PHP server to run the ReactJS dev server created using yarn start within a directory named /reactive on the PHP site (using nginx proxy_pass). The problem is that I cannot set the root of the node server to ...

Determine whether the current page was reached by pressing the back button

Can we determine if the current page was loaded via a back button press? Here is the scenario: index.html (contains a link to page1 in the menu) page1.html (loads content from ajax with a link to page2) page2.html (user presses the BACK button) page1.h ...

Incorporating dynamic content changes for enhanced user experience can be achieved more effectively with AngularJS

I am utilizing a REST service to retrieve information for a banner. The goal is to dynamically update the slider on the main page using this data. Currently, I am using $http.get to fetch the data, and then implementing interpolation with additional ng-if ...

What is the best way to run a code block every time a new reaction is added in discord.js?

I need assistance with creating a bot that can count the number of specific reactions ('⚪') to a message within a specified time frame. Additionally, I want to be able to skip the remaining time by reacting to a different emoji ('X'). ...

Use mongoose's Model.update() method for updating specific values only

I am working with a specific schema that defines certain default values: const wordSchema = mongoose.Schema({ author: {type: String, index: true, default: 'unknown'}, quote: String, source: {type: String, default: 'unknown', inde ...

Transfer data as JSON from Flask to JavaScript

Having trouble sending data from Flask to JavaScript. I have the information from the database and added it to a dictionary. Now, I want to convert this data into a JSON object in JavaScript to display it on a map. Despite using JSON.parse in JavaScript, i ...

Angular 2: The window.crypto.subtle.importKey function functions properly on 'localhost' but encounters issues on an 'ip' address

As a newcomer to Angular 2, I am working on creating a login form that encrypts and sends the user's emailid and password to the server. I have successfully implemented AES-ECB using AES-CTR from the following link: https://github.com/diafygi/webcry ...

Challenges regarding variable scope in JavaScript

Presented below is the JavaScript code I am currently using, which involves jQuery: function language(language) { var text = new Object(); $.ajax({ type: "GET", url: "includes/xml/languages/" + language + ".xml", dataType: ...