Guide on utilizing mongoose for handling multiple increment operations

Currently, I am developing a program that tracks different "accepts" and "denies". In this project, I am utilizing the findOneAndUpdate function from mongoose. However, I am encountering some issues with achieving the desired functionality. The data I am working with includes 6 values: userID, accept, deny, nsfw, copyright, and invalid_format.

Displayed below is the code snippet:

if (interaction.customId === 'accept') {
         

                
    leaderboard.findOneAndUpdate(
        {
            userID: interaction.user.id
        },
        {
            userID: interaction.user.id,
            $inc: { accepts: 1 }, // Increment accepts by 1

        },
        {
            upsert: true, new: true
        }, (err: any, doc: any) => {

            if (err) console.log(err)

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

}


if (interaction.customId === 'deny') {
          
    leaderboard.findOneAndUpdate(
        {
            userID: interaction.user.id
        },
        {
            userID: interaction.user.id,
            $inc: { denies: 1 }, //increment the denies by 1

        },
        {
            upsert: true, new: true
        }, (err: any, doc: any) => {

            if (err) console.log(err)

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

if (interaction.isStringSelectMenu()) {

    if (interaction.customId === 'reason') {
     
 

        if (reason === 'nsfw') {
            // Find the user in the database and increment the nsfw field by 1
            leaderboard.findOneAndUpdate({ userID: interaction.user.id }, { userID: interaction.user.ID, $inc: { nsfw: 1 } }, { upsert: true, new: true }, (err: any, doc: any) => {
                if (err) console.log(err)
                console.log(`Updated ${interaction.user.username}'s ${reason}'s to ${doc.nsfw} `)
            })
        }
        if (reason === 'copyright') {
            // Find the user in the database and increment the copyright field by 1
            leaderboard.findOneAndUpdate({ userID: interaction.user.id }, { userID: interaction.user.ID, $inc: { copyright: 1 } }, { upsert: true, new: true }, (err: any, doc: any) => {
                if (err) console.log(err)
                console.log(`Updated ${interaction.user.username}'s ${reason}'s to ${doc.copyright} `)
            })
        }
        if (reason === 'invalid_format') {
            // Find the user in the database and increment the invalid_format field by 1
            leaderboard.findOneAndUpdate({ userID: interaction.user.id }, { userID: interaction.user.ID, $inc: { invalid_format: 1 } }, { upsert: true, new: true }, (err: any, doc: any) => {
                if (err) console.log(err)
                console.log(`Updated ${interaction.user.username}'s ${reason}'s to ${doc.invalid_format} `)
            })
        }
    }

Despite my efforts, it seems to be generating new entries instead of updating the existing one with the same userID. How can I resolve this issue?

Answer №1

To successfully combine Increment and Upsert operations, you must first ensure the existence of the record before performing the increment.

Consider implementing a solution similar to this:

// Check if the user's record exists
await leaderboard.updateOne(
  { userID: interaction.user.id }, 
  { $setOnInsert: { accepts: 0, denies: 0 } }, // Default values for insert
  { upsert: true }
) 

if (interaction.customId === 'accept') {          
  leaderboard.findOneAndUpdate(
    {
      userID: interaction.user.id
    },
    {
      $inc: { accepts: 1 }, // Increment accept count by 1
    }, 
    (err: any, doc: any) => {
      if (err) console.log(err)
      console.log(`Updated ${interaction.user.username}'s accepts to ${doc.accepts} `)
    }
  )
} else if (interaction.customId === 'deny') {
  leaderboard.findOneAndUpdate(
    {
        userID: interaction.user.id
    },
    {
        $inc: { denies: 1 }, // Increment deny count by 1
    },
    (err: any, doc: any) => {
      if (err) console.log(err)
      console.log(`Updated ${interaction.user.username}'s denies to ${doc.denies} `)
    }
  )
}

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

The clash between the definitions of identifiers in this file and another (@types/jasmine) is causing error TS6200

While trying to build my project with Angular CLI, I am encountering the following error message: ERROR in ../my-app/node_modules/@types/jasmine/index.d.ts(18,1): error TS6200: Definitions of the following identifiers conflict with those in another file: ...

A guide on using Material UI - InputLabel in JavaScript

I'm currently integrating a form from this Codepen link into my project built with Codeigniter. However, I am encountering issues after incorporating material-ui into the CodeIgniter framework. The problems I am facing include an invalid token and an ...

What is the most efficient way to remove all typed characters from fields when clicking on a different radio button? The majority of my fields share the same ngModel on a separate page

Is there a way to automatically clear all typed characters in form fields when switching between radio buttons with the same ngModel on different pages? I noticed that the characters I type in one field are retained when I switch to another radio button. ...

In JavaScript, a prompt is used to request the user to input a CSS property. If the input is incorrect,

Implement a while loop that continuously prompts the user to enter a color. If the color entered matches a CSS property such as blue, red, or #000000: The background will change accordingly, but if the user enters an incorrect color, a message will be dis ...

Utilize forRoot to pass configuration data

When using Angular, I encountered a challenge in passing configuration data to a custom library. Within the user's application, they are required to provide config data to my library through the forRoot method: // Importing the custom library import ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...

After a texture is added, the shine of the Three.js MeshPhongMaterial diminishes

Check out this intriguing Codepen showcasing a white, glossy "cup" loaded using Three's GLTFLoader: https://codepen.io/snakeo/pen/XWOoGPL However, when I try to add a texture to a section of the mug, the shiny cup mysteriously transforms into a lack ...

"Using Sequelize's Op.and and Op.like operators led to an unexpected outcome of producing an empty

I am working on developing a search endpoint using express and sequelize. I noticed an issue where using Op.and in my 'where' object results in an empty object: const where = { [Op.and]: req.query.q.split(" ").map((q) => { ...

Having issues when dynamically adding options to a multiselect dropdown

I'm working on dynamically adding options to a multiselect using AJAX: <select size='2' name="CraftCode" id=@ccrf class="form-control js-select manualentrydd" ></select> $.ajax({ type: "GET", url: "GetCraftCodes", data: ...

Exploring the process of incrementing months in an Angular application

I have been using Angular for only a week now, and in my Angular 7 application I have integrated an owl date picker. The issue I am facing is that after selecting a date from the date picker, I need to increment it by 3 months. Let's assume that &apos ...

How can I use jQuery to determine the total count of JPG files in a directory

How can I use jQuery to count the number of jpg image files in my document? Here is the command to count the image files: $('#div').html($('img').length ); However, this counts all image files with the 'img' tag. Is there ...

Modify the name of the variable when sending the object to an HTTP service in Angular version 6

export class ShopModel { public id: number; public name: string; public email: string; public phone: string; public website: string; public address: string; public gst_number: string; public pan_number: string; public ta ...

The latest error in the Next.js 13 app directory: React child is not valid (detected: [object Promise])

I am currently utilizing the new app directory feature in Next.js 13. Within my project, I have a page component located at app/page.tsx. This component contains the following code snippet: "use client"; import { useState } from "react" ...

I encountered a "ReferenceError: db is not defined" while trying to call a function in Express.js with MongoDB intergr

The structure of the code is as follows: var express = require('express'); var router = express.Router(); var mongo = require('mongodb').MongoClient; function getData(){ db.collection("collection_name").find({}).toArray(function (er ...

How can I pass a value back to a koa generator function?

I currently have a setup similar to the following: var app = koa; var run = function (generator){ var it = generator(go); function go(err, res) { it.next(res); } go(); } app.use(function *() { run(function *(callback) { var res ...

What could be causing the npm server error in my Vue.js application?

After recently setting up Node.js and Vue.js, I decided to dive into my first project on Vue titled test. As part of the process, I attempted to configure the server using the command: npm run server However, I encountered the following error message: C ...

The :contains method in jQuery functions smoothly in Firefox, Safari, and Chrome, but unfortunately does not work

My code on JSFiddle is having some compatibility issues with the jQuery :contains selector specifically in Internet Explorer versions 7, 8, and 9. The code works fine in Firefox, Safari, and Chrome. You can find the working code here. I tried making the ...

Tips on saving every query outcome in a separate array and delivering it back to the controller upon completion

I am currently facing an issue where I receive data in a function from my controller, and inside my model function, I need to retrieve results using a query with a dynamic value of channel. The channel ID will be coming from each checkbox on my HTML view ...

What is the best way to personalize Material UI elements, such as getting rid of the blue outline on the Select component?

Embarking on my journey of developing a React app, I made the decision to incorporate Material UI for its array of pre-built components. However, delving into the customization of these components and their styles has proven to be quite challenging for me ...

What is the best way to eliminate a specific value within a flatmap?

This is the flatMap: const choices = names.flatMap( (item) => item.name + " - " + item.size + "- " + item.category ); console.log(choices): https://i.stack.imgur.com/MO4b1.png If the item.category is equal to S-XL, how can ...