Increment field(s) conditionally while also performing an upsert operation in MongoDB

I need to perform an insert/update operation (upsert) on a document.

In the snippet below, there is a syntactical error, but this is what I am attempting to achieve:

$inc: { {type=="profileCompletion"?"profileCompletion":"matchNotification"}: 1},

If the type (received in req.body) is profileCompletion, I want the document to look like this:

{
        "_id": "0h4wpbgy7u",
        "date": "Oct242022",
        "profileCompletion": 1,
        "matchNotification": 0
    }

Below is the current query I have:

await db.collection('emails')


.updateOne(
{
_id: userId
},
{
$setOnInsert: 
{
time: getDateMonYear(new Date()),
},
$inc: { {type=="profileCompletion"?"profileCompletion":"matchNotification"}: 1},
},
{upsert: true},
)

Answer №1

Before executing the query, it is recommended to construct the update object:

const update = { $setOnInsert: { time: getCurrentDate(new Date()) }};

if (type === 'profileCompletion') {
  update.$inc = { profileCompletion: 1 }; 
} else {
  update.$inc = { matchNotification: 1 }; 
}

...

await db.collection('emails').updateOne({ _id: userId }, update, { upsert: true });

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

Discovering the operating system and architecture type for my browser using Node.js - what steps should I take?

I am currently developing a Node.js app that serves as an API microservice. I need to retrieve the operating system and architecture type from a GET request made by my browser. One example could be: "Windows NT 10.0; Win64; x64" ...

Transform a CSV file into a JSON object containing arrays of numbers

Feeling a bit stuck on this one - any guidance would be greatly appreciated! Using primarily an online converter, or perhaps even a node package, I am attempting to transform a CSV file structured like so: Cat,31.2,31.2 Dog,35,1 Tree,32.4 into the follo ...

PhoneGap iOS application storing outdated information

My Phonegap 2.1 app running on iOS 6, with jQuery 1.7.2 and JQMobile 1.1.1 libraries, is experiencing an issue where old data from ajax responses gets cached if the app is unused for a few days. The only way to resolve this issue is by reinstalling the a ...

Changing a variable with Functions and Objects

I'm curious to know what the index variable returns in this code snippet. I believe it will be 0. function jsTest() { var index = 0; var counter = 0; var obj = {}; obj.index = index; var func = function () { for (index ...

Error encountered while trying to upload a file using PHP on a hosting platform

Hey everyone, I'm feeling really frustrated right now because I'm facing a file upload error in my PHP code. The issue is that the file is not getting uploaded to my folder and no error messages are being displayed. I've been working on cr ...

Ensuring the value of a v-text-field in Vuetify using Cypress

I am currently developing an end-to-end test suite using Cypress for my Vue and Vuetify frontend framework. My goal is to evaluate the value of a read-only v-text-field, which displays a computed property based on user input. The implementation of my v-tex ...

When the page loads, a JavaScript function is triggered

My switchDiv function in Javascript is being unexpectedly called when the page loads. It goes through each case in the switch statement, except for the default case. Does anyone know how to solve this issue? $(document).ready(function() { $("#be-button" ...

Encrypting sensitive information in JavaScript and Angular 2: SecureString

Is there a way to securely copy sensitive data to the clipboard in javascript/Angular2, ensuring that the string remains confidential by removing it from computer memory when no longer needed? In Microsoft .Net, there is a feature called System.Security.S ...

What could be causing Next.js to throw an error upon completion of the MSAL OAuth process?

I encountered an error while building a website using next.js. The site is set up for production, and after the authentication process with MSAL for Azure AD integration, I am facing the below error during the OAuth loop. As a beginner in next.js coming fr ...

Exploring ways to display dynamic content within AngularJs Tabs

I need help figuring out how to display unique data dynamically for each tab within a table with tabs. Can anyone assist me with this? https://i.stack.imgur.com/63H3L.png Below is the code snippet for the tabs: <md-tab ng-repe ...

Combining a standard JSS class with Material-UI's class overrides using the classnames library

I am exploring the method of assigning multiple classes to an element in React by utilizing the classnames package from JedWatson, along with Material-UI's "overriding with classes" technique. For reference, you can see an instance in MUI's docu ...

Guide to implementing bidirectional data binding for a particular element within a dynamic array with an automatically determined index

Imagine having a JavaScript dynamic array retrieved from a database: customers = [{'id':1, 'name':'John'},{'id':2, 'name':'Tim}, ...] Accompanied by input fields: <input type='text' na ...

Struggling to find a solution for your operating system issue?

We are currently attempting to utilize the markdown-yaml-metadata-parser package for our project. You can find more information about the package here. Within the package, it imports 'os' using the following syntax: const os = require('os ...

Having issues updating table with Javascript after form submit in IE and Edge browsers

My current setup involves using Contact Form 7 in Wordpress to store data in a MySQL Database with Submit-Form. Now, I am working on reloading a table containing this data after the form submission. Here is the script I am currently using: /* FORM RELOAD ...

When attempting to deserialize a 2D array in JSON, it unexpectedly returns as a string instead of

I am trying to figure out how to deserialize the JSON string provided below into a two-dimensional array object using JavaScript. Whenever I attempt to use JSON.parse or eval, it ends up getting converted into a string format. Currently, I am utilizing D ...

What is the method for inserting data into an array of objects in JavaScript?

I have a question regarding how to push/replace data into an object of an array of objects. Please excuse any mistakes in my grammar. Here is my dummy data: const dummyData = { id: 1, daerah: "Bandung", date:"1668790800000& ...

Encountering an error while attempting to launch an AngularJS application on Node.js? Let's

Currently, I am in the process of learning Angular. Whenever I attempt to run my code, an error message pops up: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f7a737a7c6b6d70715f2b312f3115">[email protected]< ...

Using Jquery colorbox to redirect or forward within the current colorbox container

I am facing a challenge with a colorbox that is currently loaded. I am looking for a way to redirect or forward to another page within the existing colorbox. window.location = href; does not seem to be effective in this situation. EDIT: To be more precis ...

Is it possible to use multiple routes in the same page with Vue-router?

In the process of developing a Vue-based web application that utilizes vue-router in history mode, everything was functioning smoothly for navigating between various pages. However, a new request has been made to open certain pages within a virtual dialogu ...

I am having trouble calling a method in the subscribe function because it is showing an error message saying "Cannot read property 'showMessageFromSocket' of undefined"

My goal is to call a method within the subscribe block, but I am encountering an error that says "Cannot read property 'showMessageFromSocket' of undefined". How can I successfully call the showMessageFromSocket method? In Angular, this was possi ...