Ways to continuously reduce the value in Mongo until it reaches zero

singleObj = await Objects.findByIdAndUpdate({ _id: req.body.id, }, { $inc: { 'total_obj': -1, 'total_stuff': 1 }, }, { new: true })

Whenever the user clicks a button, we decrement the value of 'total_obj' by one. It's important to note that the value can be zero or greater. I attempted to achieve this using the following code:

singleObj = await Objects.findByIdAndUpdate(
  { _id: req.body.id, "total_obj": { "$lt": 0 } },
  { "$set": { "total_obj": 0 } }
);

Unfortunately, this approach causes issues every time the page is loaded and sets the values to 0. I also included the following definition in the schema:

total_obj: {
    type: Number,
    required: true,
    min: 0
},

Answer №1

It seems like you're looking to ensure that your value doesn't go below 0. To achieve this, you should employ the $gt operator. While you correctly utilized the $inc operation in the initial findByIdAndUpdate, it appears that you overlooked using it in the subsequent one.

Additionally, if we are not only targeting the id, then it's advisable to make use of findOneAndUpdate instead.

singleObj = await Objects.findOneAndUpdate(
   { _id: req.body.id, "total_obj": { "$gt": 0 } },
   { $inc: { "total_obj": -1 } }
);

Answer №2

Make sure to retrieve the Objects object first and only update the value if it is greater than zero:

const obj = await Objects.findById(req.body.id)
if (!obj) // Issue: object not found
if (obj.total_obj > 0) {
    obj.total_obj = obj.total_obj-1
    await obj.save()
} else { 
    // The `total_obj` value is already zero 
}

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

Obtain the Percentage Matched attribute expressed as a percentage through MongoDB

In my scenario, I need to input a list of properties into MongoDB that will be used to search for results matching at least 90% of the properties provided. For example, let's say we have the following data: [ { id: 1, properties: ...

The Automatic Submission Feature of Number Inputs in Android and HTML5

Currently, I am developing a web page that includes a form with a single field for entering a zip code to estimate shipping and taxes. My goal is to have the form submit when the user presses the enter key on the numeric keypad. For example: <form met ...

What is the method for setting a variable to an object property's value?

I am currently working on a React app and I have an object structured like this: state = { property1: 'value', property2: 'value', property3: 'value', property4: 'value', } I am trying to write a fu ...

PHP results can be manipulated with jQuery and JavaScript

I have a unique jQuery script that is designed to insert custom content after each paragraph in news articles. Here's an example: $(document).ready(function() { $("<a>The link inserted in jQuery</a>") .insertAfter("p") ...

The efficiency of Testing Library findBy* queries is optimized when utilized alongside async/await functionality

After reviewing the documentation, it was noted that queries made using findBy return a Promise. Interestingly, utilizing these queries with Promise.prototype.catch() seems ineffective in comparison to pairing them with async/await + try...catch. An insta ...

Array containing two objects in a two-dimensional format

In the example provided, I am working with a 2D array. Link to the example: https://codesandbox.io/s/v0019po127 I am noticing different results depending on whether I use the browser console or Codesandbox's console. I have attempted using JSON.str ...

Animate CSS Grid to dynamically fill the viewport on top of current grid elements

Please note that I am specifically seeking vanilla JS solutions, as jQuery is not compatible with this project I have a grid structure that is somewhat complex: body { margin: 0; height: 100vh; text-align: center; } .grid-container { ...

In search of the most efficient method for integrating an AJAX-powered TreeGrid feature

Can anyone recommend an Ajax/TreeGrid implementation that meets the following criteria: Must support server side sorting Should be able to load leaf nodes on demand, meaning only children of open nodes are loaded Needs to support paging so that nodes are ...

Generating a request to API using Express and create-react-app

I have my create-react-app running on localhost:3000 with a proxy set up in package.json to point to my server running at localhost:3001. { "name": "my-app", "version": "0.1.0", "private": true, "dependencies": { "axios": "^0.18.0", "react ...

Preserve the selected option's value when transferring a page using PHP and JavaScript

Hey everyone, I have a question and could really use some help. I've encountered an issue where I'm generating a select with options pulled from a database, and then sending the information through a post action using PHP. What I'd like to ...

Guide on transforming a specified string into a modified regex string using JavaScript

Here are some example strings: 2222 333333 12345 111 123456789 12345678 The expected result is: 2@222 333@333 12@345 111 123@456@789 12@345@678 In other words, the character '@' should be inserted at the 4th, 8th, 12th, etc. position ...

Adjust the text color of ASP.Net Label based on the presence of a hyphen

I need help changing the text and font color of my ASP.net label based on its content. The label displays a percentage change, and I want negative numbers to be shown in green and positive numbers in red. However, when I try to implement this, I keep enc ...

I can't figure out why I keep receiving the InvalidArgumentError for H.Map with Argument #0 [object Object]

I recently refactored the code taken from the Maps API for JavaScript "Working with React" section. As a beginner in React and currently learning it in school, I have to utilize functional components. The material provided guidance on class component syn ...

manipulating session variables with javascript ajax and php

I'm struggling with setting and retrieving session variables using JavaScript code that calls PHP functions via AJAX. I want to access the returned session field in my JavaScript, but nothing seems to be working. Can someone take a look at my code and ...

What causes an array to accumulate duplicate objects when they are added in a loop?

I am currently developing a calendar application using ExpressJS and TypeScript. Within this project, I have implemented a function that manages recurring events and returns an array of events for a specific month upon request. let response: TEventResponse ...

Using Database Data in a Material UI Select Component

I'm having trouble populating a select component from Material UI with data retrieved from my database. Although I can display the data in the component, upon selecting an option it breaks and displays the error "categorias.map is not a function". Any ...

Acquiring HTML Element Data with Clojure

As a beginner in the world of web development, I have chosen Clojure as my backend language. I am currently in the process of transitioning my user authentication from frontend to backend, and specifically trying to extract the value from an HTML password ...

How can I inquire about both a Mongodb document and a reference object simultaneously?

I am currently working on developing a filter system to organize orders for sellers. The orders consist of various components such as "price," "country," "product type," as well as seller and customer information. order: { _id:"", price: $750, country:" ...

Utilizing the mobile navigation layout for desktop screens without the need to adjust breakpoints

Having created a responsive site with common breakpoints established in SCSS as mixins, I am now seeking to implement the mobile breakpoint for a single page on desktop view only. Initially, my plan was to create a 'forced-mobile' class by exten ...

Tips on utilizing $watch in this context to ensure the API is activated prior to the Directive, incorporating ui-router

I am currently using a ui-router and I have a question regarding the resolve function. Is it possible to use resolve with the following state configuration: state: { url: "/summary", templateUrl: '../script/planSummary.html', co ...