What is the best way to utilize findOneAndUpdate() in Mongoose while maintaining a consistent value?

I have a programming challenge where I need to increment one value if condition x is true, and another value if condition y is true. The issue I'm facing is that my current system also resets the value that is not being updated back to 0, which is not desired. I am looking for a solution to prevent this from happening and keep the other value unchanged.

Below is the snippet of code I am working with:

leaderboard.findOneAndUpdate(
{ 
    userID: interaction.user.id 
}, 
{
    userID: interaction.user.id,
    $inc: { accepts: 1 },
    denies: 0
}, 
{ 
    upsert: true, new: true 
},  (err: any, doc: any) => {

if (err) console.log(err)

console.log(`Updated ${interaction.user.username}'s accepts to ${doc.accepts} `)
})

In this scenario, I want the 'accepts' value to be incremented by 1, while keeping the 'denies' value the same as it is already stored in MongoDB.

Answer №1

Consider adjusting your update query as follows:

{ $inc: { approves: 1 } }

It may not be necessary to use upsert in this scenario because it could result in creating a new document with just the approves field.

{ upsert: true, new: true }

If you do need to use upsert, tailor your update query according to the desired value to set. For example,

If (x) {
  updateQuery = {
    userID: interaction.user.id,
    $inc: { approves: 1 },
  }
} else {
  updateQuery = {
    userID: interaction.user.id,
    $inc: { declines: 1 },
  }
}

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

Is there any variation in the Stripe payments Workflow when utilizing the Connect-API?

I have a question about simplifying the implementation of the Stripe API for multiple products on a single page. Currently, I have a webpage with 20 different items and I am utilizing Stripe Connect. Instead of creating individual forms for each product i ...

Enhance text search functionality using AngularJS

Just starting to learn angularjs. Below is the code I've written: $scope.styles = [{"name":"walking"},{"name":"Food"},{"name":"culture"}] I have created a checkbox list <div ng-repeat="style in styles"> <input type="checkbox"> {{ ...

ADT codec encounters compilation issues

Currently, I am utilizing the scala driver to perform IO operations with mongodb. Specifically, my scala version is 2.11.11 and the mongo db driver version is 2.2.0. While referencing the documentation on ADT, I stumbled upon the following example: seal ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

What are the main challenges in resolving dependencies and implementing best practices when it comes to updating an outdated Angular NodeJS

After several months away, I am now faced with the challenge of updating and maintaining an out-of-date angular project. Seeking advice from experienced developers on how to tackle this situation. Previously, I used NPM update or upgrade commands to keep ...

Transforming a StringDate into a format that can be easily queried. Aggregating and calculating the total values for today, yesterday, the current

As I pondered over tackling the given question, it dawned on me that it had two parts. The first part involved my collection dates being stored in a plain string with a mysql format (YYYY-mm-dd HH:mm:ss), and the second part was about projecting the summar ...

When making an AJAX request, ensure the response is in JSON format with individual properties rather than as a single

Here's an example of an AJAX request with JSON dataType: JavaScript: function checkForNewPosts() { var lastCustomerNewsID = <?php echo $customers_news[0]['id']; ?>; $.ajax({ url: "https://www.example.com/check_for_n ...

Unable to locate the reverse for 'my_views_name' without any arguments in Django. Bridging server-side code with client-side JavaScript using jQuery

How can I create a button to update a URL after fetching data from the database using jQuery AJAX? This is my code in views.py: def list_maingroup(request): lists = MainGroup.objects.all().order_by('-pk') data = [] for i in lists: ...

Positioning customized data on the doughnut chart within chart.js

Is there a way to customize the position of the data displayed in a doughnut chart? Currently, the default setting is that the first item in the data array is placed at 0 degrees. However, I need to place it at a custom position because I am working on a ...

There was a TypeError encountered in angular-highcharts, stating that it is not possible to read the property '0' of an undefined

Currently, I am utilizing the angular5 framework in conjunction with the angular-highcharts library to generate a basic map based on the highcharts demonstration available at https://www.highcharts.com/maps/demo/category-map. Here is a snippet of the code: ...

Passing a variable via routes using Express

app.js var express = require('express'); var app = express(); var textVariable = "Hello World"; var homeRoute = require('./routes/index'); app.use('/', homeRoute); index.js var express = require('express'); var ...

Adding choices to dropdown menu in AngularJS

As a beginner in AngularJs, I am struggling with appending options to select boxes created by javascript. Below is the code snippet that is causing the issue. var inputElements = $('<div><label style="float:left;">' + i + '</ ...

There seems to be an issue with displaying the meta information in a Nuxtjs project using this.$

I am facing an issue with meta information in a Vue page. When I try to access "this.$route.meta", it does not display any meta information. However, when I inspect the Vue page element, I can see that there is indeed meta information present. How can I ...

Trouble with Bootstrap v4 toggle drop-down menu functionality detected in local environment, yet functions correctly when live on the

Today, I've encountered an issue with my Bootstrap v4 collapsible hamburger menu on my local XAMPP server. Interestingly, the menu works perfectly fine on my public website when the display is 768px wide in Chrome and Firefox. I have searched through ...

Set a timer to run only during particular hours of the day, and pause until the next designated time

I need assistance with integrating a function called "tweeter" into my code so that it runs at specific times throughout the day - 09:00, 13:00, 17:00, and 21:00. Currently, the function runs continuously after the initial hour check is completed, instead ...

How to output a string in jQuery if it includes a certain character?

I need to extract all strings that include a specific word within them, like this: <div> <div> <span> <h3>In Paris (Mark Bartels) worked for about 50 years.</h3> </span> </div> ...

Is it possible to read JSON data from a POST request using Django DRF?

When attempting to send data via a jQuery POST request, I am able to access the data from both the JavaScript client side and the Python Django Rest Framework serializer create method on the backend. The console.log output is: { "wo_r": [ { " ...

Adjusting color of fixed offcanvas navbar to become transparent while scrolling

After creating a navbar with a transparent background, I am now using JavaScript to attempt changing the navigation bar to a solid color once someone scrolls down. The issue is that when scrolling, the box-shadow at the bottom of the navbar changes inste ...

What is the best way to add an Angular 2 component to a D3 selection?

I have implemented a chart using Angular2 and d3js with a tooltip that appears when hovering over the chart. Currently, I am directly appending a "div" element to the body and dynamically generating the innerHTML when the mouse moves within the d3.select(" ...

Exploring Ways to Navigate to a Component Two Steps Back in Angular

Let's say I have three routes A->B->C. I travel from A to B and then from B to C. Now, is it possible for me to go directly from C to A? ...