Discover products that are the same as or lower than the quantity received mongoose

I am looking to retrieve elements where the stock is less than or equal to the quantity received from a request.

Within my product document, there is a property called stock that needs to be compared with the quantity of the products in the request, which are stored in an array containing order information.

Data request: https://i.sstatic.net/CmMg1.png

To identify products with stock quantities equal to or lower than those requested, I am implementing the following logic:

let productHasStock =   async ( req, res, next ) => {
    
    const details = req.body.detail;
    let ids = [];
    let stock = [];
    
    const products = details.map( detail => {
        ids.push(detail._id),
        stock.push(detail.quantity)
    });

    const product = await Product.find({ stock: { $lte: stock } }).where('_id').in(ids);
}

However, using $lte with an array as input does not work since it requires an integer value.

The scenario works if approached this way:

const product = await Product.find({ stock: { $lte: 20} }).where('_id').in(ids);

Yet, I am seeking guidance on how to carry out this operation using the quantity data from the request and properly validating it against the available stock.

Answer №1

Initially, you are comparing the stock in findQuery with an array because you defined stock as an array.

let productHasStock =   async ( req, res, next ) => {

const details = req.body.detail;
let ids = [];
let stock = []; // here stock is array type

const products = details.map( detail => {
    ids.push(detail._id),
    stock.push(detail.quantity)
});

const product = await Product.find({ stock: { $lte: stock } }).where('_id').in(ids); // here you are comparing array it should be integer.

}

Moreover, if your stock=['5','100'], then why pass an array while comparing stock in the database? Knowing that the larger value in stock is 100, you should only compare with 100 since you only want products with stock less than or equal to 100.

const product = await Product.find({ stock: { $lte: 100} }).where('_id').in(ids);

Additionally, you should first find the largest value from the array and then use that in the query.

If you intend to compare a product's id and then its stock specifically, the current logic may not be optimal. Consider using an aggregate pipeline in Mongoose to locate the specific product by id and compare its stock as well.

Answer №2

The task at hand seems to involve identifying stock purchase requests that cannot be fully met. Each request can serve as a condition in the search "$or" operation. It is important to remember that you will still have to convert the data request into the search query.

db.Product.find({
  // Each data request forms part of "$or"
  "$or": [
    {
      "_id": 0,
      "stock": { "$lte": 200 }
    },
    {
      "_id": 2,
      "stock": { "$lte": 100 }
    },
    {
      "_id": 5,
      "stock": { "$lte": 500 }
    },
    {
      "_id": 7,
      "stock": { "$lte": 300 }
    }
  ]
})

Test it out on mongoplayground.net.

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

Steering clear of inserting 'Array' into a database through autocomplete using Js, Ajax, and Json

I'm currently working on a script that auto-populates input fields based on the autocomplete feature of the first input field. Although the script works fine and everything looks good when I hit submit, the problem arises when I check the database. A ...

A more efficient method in jQuery to detach and re-attach elements

Apologies for not having a more creative title. I am interested in finding a better, more concise way to write the function below. Specifically, I would like to simplify the process of moving elements around. The function is designed to create a parent di ...

Issue with jQuery sortable serialization when dynamically adding content is not being recognized

I've been attempting to re-order a list through ajax on sortable update. However, when I add a new item to the list via ajax after the sortable has already been initialized upon page load, it fails to recognize the new item with the "serialize" functi ...

Is there a way to export a specific portion of a destructuring assignment?

const { a, ...rest } = { a: 1, b: 2, c: 3 }; If I want to export only the rest object in TypeScript, how can I achieve that? ...

What is the best way to include a JavaScript function in a dynamically generated div?

By clicking a button, I am able to dynamically generate a table row that contains a div element with the class "contents." $(document).on("click", ".vote", function() { // Removing selected row var rowLoc = this.parentNode.parentNode. ...

Troubleshooting an ETIMEDOUT error in Node.js when using Sequelize with MySQL

I recently followed a tutorial at the following link: Despite having the same code as the tutorial, I keep encountering an error with my port configuration. Here is the error message: Server is running on port 3000. (node:22880) UnhandledPromiseRejectionW ...

Tips for maintaining state URL persistence after a page refresh in Next.js 13 when utilizing next-usequerystate

Currently, I am using the next-usequerystate library with Next Js 13. However, I have encountered an issue where the state on the URL is lost when I refresh the page. The initial URL looks like this: localhost:3000/?page=1&genres=tree But upon refres ...

Components for managing Create, Read, Update, and Delete operations

As I embark on my Angular 2 journey with TypeScript, I am exploring the most efficient way to structure my application. Consider a scenario where I need to perform CRUD operations on a product. Should I create a separate component for each operation, such ...

Do multiple requests in an Express.js API server cause blocking issues?

My API server is set up with an endpoint that retrieves, sorts, and calculates data from a MySQL database. The endpoint URL structure is as follows: http://localhost:3003/widgetData/$userId/$widgetId/$startDate/$endDate/ The $widgetId parameter specifie ...

Guide on automatically refreshing an iframe when the source is set to X using JavaScript

I am attempting to create a code that automatically refreshes an iframe window if the source is set to 'http://www.url.com', but does not refresh if the iframe has a different source. Is there a method to achieve this? ...

The checkValidity function fails to identify incorrect "tel" input

In my form, I am using the checkValidity function to validate inputs. However, I have encountered an issue where the validation only works when an input with the required attribute is missing a value. It doesn't work if there is a value type mismatch, ...

Struggling with getting a dropdown to switch the currently displayed image

I am working on a project that involves displaying a series of 4 images which can be clicked on to reveal a drop-down menu. The selection made in the drop-down menu should change the image to correspond with the choice. Here is the current code I have impl ...

Error occurred due to an abrupt termination of JSON input while transferring data through ajax communication

<script> $.ajax({ type: "POST", url: "http://localhost:3000/xot/us/confirm", crossDomain: true, dataType : 'json', contentType: "application/json; charset=utf-8", data:JSON.stringify({ username:"User" ...

All custom routes within Next.js are re-rendered with the use of a customized express server

I have configured a custom express server in my server.js file following the example provided in the Next.js documentation. However, whenever I visit any dynamic routes defined there, the app re-renders, causing a flash of unstyled content. Is there a way ...

How to achieve a successful response with Ajax and jQuery?

I'm currently working on practicing data retrieval through an API using jQuery. After watching a few YouTube tutorials, I still can't seem to get a successful response... it's quite frustrating. Aside from YouTube, I'm also a subscribe ...

The error message "nuxt: not found" is indicating that the Nuxt framework is not being recognized or is

Encountering an issue during the deployment of a server-side nuxt app with an express server on Heroku. The build process is successful, but upon startup, the following error occurs: 2021-07-29T18:13:38.000000+00:00 app[api]: Build succeeded 2021-07-29T18: ...

Implementing a feature that loads older posts on a webpage as users scroll down

Spent hours trying to get my site to automatically load older posts on scroll down with no luck. Any assistance is greatly appreciated :) After researching, [this tutorial][1] seemed like the best solution so I followed it step by step and integrated ever ...

Tips for preserving filled data field values prior to database saving in React

For a conference management application, I built a React application with Redux. One of the features I included is a form for adding new conference information. Dilemma My current challenge is that if a user navigates away from the form halfway through f ...

Fundamental inquiry regarding XMLHttpRequest

Having some difficulty with my JavaScript code calling PHP. Can someone find an error in this code snippet? I'm sure I've used similar code elsewhere on the site... var xmlHttp = createXmlHttpRequestObject(); var favSongArray = []; function cr ...

Headers with a 3 pixel stroke applied

I have a design on my website that includes a 3px stroke around the header text to maintain consistency. I don't want to use images for this due to issues with maintenance and site overhead. While I know about the text-stroke property, browser suppor ...