Tips for updating multiple documents in a MongoDB database using an array of values

I have a range of Product items in my inventory and when a client places an Order, they submit an array of objects. Each object in the array includes the _id product (objectId) and the quantity they purchased.

[
{producId: "dshsdsdh72382377923",
quantity: 20
},
{producId: "dsh673sdh72382377923",
quantity: 10
},
{producId: "hjddjkdjkdj676372373",
quantity: 5
},
]

I would like to query the Product Collection and update the numberInStock of each product by subtracting the quantity bought by the client! Is there a way to achieve this?

Answer №1

Generate a dynamic query based on the number of items purchased by the user. Choose the product using its productId and reduce the quantity by the value in customerValue

const customerValue = 3; // Assuming the customer purchased 3 items
const queryObj = {};
queryObj['quantity'] = -customerValue;
db.collection.updateOne(
 {producId : "jkdjhfduf3223434"},
 {$inc: queryObj}
);

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 could be causing one of my images to not appear on my Gatsby page?

Hey there, I could use some help with this issue: Recently, I created a website using Gatsby.js and deployed it to my web server (which is running NGINX on Ubuntu 20.04). The site uses Gatsby Image for querying and displaying images, and everything seems t ...

What is the best way to invoke a function that is saved in an array of options while using setTimeout() within an AJAX callback?

Below is the pertinent code snippet: success: [ setTimeout(function () { ajax.success }, 250), //... An interesting observation I made is that I am able to invoke ajax.success from inside the success ...

I am looking to dynamically load a script only after retrieving specific data from a JSON file in Next.js

I am trying to ensure that the Script tag loads after the data.post.content is loaded within the HTML. Specifically, my goal is to execute the MathJax.js script inside the HTML. This is the code I have: return ( <div> <h1>{data.post ...

Determining the width of an element in terms of percentage

My issue involves input elements with widths set as percentages in CSS under the common class 'display-class' For example: input.test1 { width: 60% } In JavaScript, I am attempting to wrap a div around these input fields with the same width ...

Interested in discovering the ins and outs of the JavaScript Map function?

Currently, I am delving into this JavaScript function: function solution (array, commands) { return commands.map (v => { return array.slice(v[0] -1, v[1]).sort((a, b) => a - b).slice(v[2] -1, v[2])[0]; }); } I am puzzled about th ...

Utilizing React with an alternative server-side language

I have a small PHP backend for my website and I want to incorporate React on the front end. However, being new to front-end development and React, I am finding this process confusing as most online examples assume a JavaScript backend with Node modules. W ...

Accessing the session object within an Express middleware function is crucial for

This is my unique Express middleware setup: var app = express() .use(express.cookieParser()) .use(express.session({secret: 'HiddenSecret'})) .use(express.bodyParser()) .use(function displaySession(req, res, next) { consol ...

Disallow users from closing the tab or browser window

Is it feasible to create a loop on window.onbeforeunload that opens the current page repeatedly upon tab exit? Take a look at the code below - it works, but browsers may block it as a popup. window.onbeforeunload = function(e) { window.open(do ...

Utilize Javascript to interact with specific Objects

Working with Node.js, I have written a code that produces the following output: entries: [ { data: [Object] }, { data: [Object] }, { data: [Object] }, ... { data: [Object] } ] } null The code snippet is as follows: targetingIdea ...

Encountering issues during the transition to the updated react-native version 0.70 has posed a challenge for

Help! I encountered an error and need assistance fixing it. I've tried clearing my cache but that didn't work! The error is a TypeError: undefined is not a function in the JS engine Hermes. It also shows an Invariant Violation: Failed to call in ...

Certain public files in Express cannot be accessed locally

While running my Node.js application on localhost, I am able to access http://localhost:3000/css/dashboard.css without any issues. However, when attempting to access http://localhost:3000/css/logo.png for a logo image in the same directory, all I receive i ...

Error: Discord.js was unable to access the 'id' property because it was undefined

I need help with my ticket system project where I am trying to create a channel and send an embed in that channel. However, when I run the code, I encounter the error message TypeError Cannot read property 'id' of undefined. Here is the snippet ...

Tips for presenting HTML source code with appropriate tag coloring, style, and indentation similar to that found in editors

I need to display the source code of an HTML file that is rendered in an iframe. The source code should be shown with proper tag colors and indentations similar to editors like Sublime Text. https://i.stack.imgur.com/IbHr0.png I managed to extract the sour ...

How can we accurately identify the server that initiated an AJAX call in a secure manner?

Imagine a scenario where Site A embeds a JavaScript file from Server B and then makes a JSONP or AJAX request to a resource on Server B. Is there any foolproof way for Server B to determine that the specific JSONP request originated from a user on Site A, ...

Is there a way to easily identify the error in my Express application that is preventing my hbs template from running properly?

I am facing an issue with my express code where it is not rendering the data properly. Can someone please assist me in resolving this error? Your help will be greatly appreciated! let express=require('express'); let app=express(); ...

"Combining multiple attributes to target elements while excluding specific classes

My dilemma lies in the following selector that identifies all necessary elements along with an extra element containing the "formValue" class which I aim to omit $("[data-OriginalValue][data-OriginalValue!=''][data-TaskItemID]") ...

What could be causing a momentary 404 error when I click on a next.js `Link` that connects to an API endpoint before redirecting to the intended page?

Hello there, I recently followed a tutorial on adding authentication with Passport to Next.js from this resource: https://auth0.com/blog/next-js-authentication-tutorial/ However, I encountered a minor issue. When I click the "/login" Link in my Next.js ...

Prevent further triggering of the .click function when the user clicks repeatedly

Is there a way to prevent the .click function from executing if the user clicks too many times? This is my current code: $('button').click(function() { $('#bg').fadeToggle('200'); }); Check out the jsfiddle DEMO ...

Difficulty encountered when applying a CSS class with JavaScript

The Javascript function I am currently using is able to select multiple links. This behavior occurs because of the Regular expression I applied with the '^' symbol. I decided to use this approach because my links are in the following format: htt ...

using javascript to access an opened html div

I am making an AJAX request in A.html and once the response is successful, I want to display a message in B.html. (The message should be displayed in a div with the id='mes_div' which is located in B.html.) How can I access B.html and how do I ac ...