limit mongoose search results to a specific year

Would it be possible to add an option for the api user to filter the wine query by year? However, if no year is specified, mongoose should not return an empty array. The same applies to the price property.

For example, http://localhost:1234/api/wine?year=2010 should return wines from 2010.

http://localhost:1234/api/wine should return all wines (limited to 10).

I have successfully implemented other filters as shown below. Is this the most efficient way to achieve this?

Thank you

controller

  getWines: async (req, res) => {
    try {
      const types = ['red', 'white'];
      let {
        limit = 10,
        page = 1,
        // sort = 'asc',
        search = '',
        type = 'all',
        year = undefined,
      } = req.query;
      if (page === '0') {
        return res.json({ error: 'Invalid page' });
      }
      type === 'all' ? (type = [...types]) : (type = [req.query.type]);
      const response = await Wine.find({
        name: { $regex: search, $options: 'i' },
      })
        .where('type')
        .in(type)
        // .where('year')
        // .equals(parseInt(year))
        // .sort(sort)
        .limit(limit)
        .skip((parseInt(page) - 1) * limit);
      res.json(response);
    } catch (error) {
      console.error(error);
    }
  },

documents sample

[{
"_id": "63952372129acf895c427240",
        "name": "Chateau Leoville Barton",
        "year": 2010,
        "type": "red",
        "domain": "Saint-Julien",
        "quantity": 750,
        "price": 169,
        "quality": 100,
        "image": <<<<LONG_URL>>>>
},
{
        "_id": "639523e7129acf895c42c238",
        "name": "Chateau La Mission Haut Brion",
        "year": 2014,
        "type": "red",
        "domain": "Pessac-Leognan",
        "quantity": 750,
        "price": 219,
        "quality": 94,
        "image": <<<<LONG_URL>>>>
}]

Answer №1

To improve your search results, you can create a filter based on the conditions of both the name and type. If the query parameter year is present, include an additional condition in the filter.

const filters = {
  name: { $regex: searchTerm, $options: 'i' },
  type: { $in: wineTypes },
};

if (searchYear) {
  filters.year = parseInt(searchYear);
}

const results = await Wine.find(filters)
  .limit(maxResults)
  .skip((parseInt(currentPage) - 1) * maxResultsPerPage);

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

Encountering NaN for length within an object in node.js using the Express framework

app.post('/add', (req, res) => { const newEntry = { id: entries.length + 1, Text: req.body.text, Type: req.body.type } entries.push(newEntry) console.log(entries.slice(-1)) res.json(newEntry) }) id: entries.length + 1, ...

Enhancing Communication Between JavaScript and PHP

Positioned within my form is an input field where users can enter their postcode. The shipping cost for their order will be determined based on this postcode, utilizing PHP to assign different costs depending on the zone. After the user enters their postc ...

Exploring the power of Express.js by utilizing local variables and rendering dynamic views

I am in the final stages of completing an application using node.js and express, even though I am still relatively new to them. Here's my situation: In my app.js file, I have declared a variable app.locals.webLang and set its initial value to "EN". T ...

Creating dynamic class fields when ngOnInit() is called in Angular

I am trying to dynamically create variables in a class to store values and use them in ngModel and other places. I understand that I can assign values to variables in the ngOnInit() function like this: export class Component implements OnInit{ name: st ...

Tips for halting all YouTube videos in a Reactjs environment

I am currently working with React.js and using Next.js. I have implemented a "YouTube video slider" and now I am looking for a way to stop all videos when a button is clicked. Can anyone provide guidance on how to achieve this? Below is the code snippet ...

Error loading 'endpoint': The 'If-Modified-Since' request header is not permitted by the Access-Control-Allow-Headers in the preflight response

I have successfully created an API service using nodejs which works perfectly when accessed through the browser. However, I am facing an issue when trying to call it from a web application (MEAN app). The error message states: "Failed to load http://localh ...

Retrieve all records that contain a specific field using Mongoose

I am trying to retrieve documents from my schema that have a string field called companyName. The object I receive from the query string looks like this: {companyName:"Amazon,Microsoft"}}. How can I find and return all documents that have a compa ...

Converting JSON data types into TypeScript interface data types

Struggling to convert data types to numbers using JSON.parse and the Reviver function. I've experimented with different options and examples, but can't seem to figure out where I'm going wrong. The Typescript interface I'm working with ...

Extract attributes from a string of HTML containing name-value pairs

Here is a sample string that I need to work with '<img id="1" data-name="test" src="img_01.jpg" />' My goal is to extract the attribute name and value pairs from the string, create the element, and apply these attributes. I have come up ...

The timepicker is set to increment by 30-minute intervals, however, I would like the last time option to be 11:

I am currently using a timepicker plugin and am trying to set the last available time option to be 11:59pm. Despite setting the maxTime attribute in my code, the output does not reflect this change. Any suggestions on how to achieve this would be highly ap ...

Refreshing CKFinder Form Field with jQuery

Looking to update the value of an input field .ckfinder-input using CKFinder's pop-up image selector. Everything runs smoothly until attempting to assign the selected image URL to the input field with input.val() = fileUrl, resulting in the error mess ...

How to write an aggregation query in Java using the MongoDB driver version 3.4?

Can someone assist me in writing the equivalent Java query for driver version 3.4 of this aggregation query: db.getCollection('MYTABLE').aggregate([ {"$match": { "ID_STATUSMATRICULA": 1 } }, {"$group": { "_id": null, ...

Tips for sending API requests as an object rather than an array

Hello there! I'm having trouble posting the data as an object. I attempted to adjust the server code, but it keeps throwing errors. Here is a snippet of the server code: const projectData = []; /* Other server setup code */ // GET route app.get(&a ...

Steps for refreshing a React component following a data fetch operation

Currently, I am in the process of learning how to use React for building web applications. I have a basic React app that demonstrates the following features: Fetching a list of users Displaying the names of the users on individual cards once they are fetc ...

What is the best way to receive a user's input date in Dynamics 365 using HTML/JavaScript?

My HTML webform is set up to capture user input like address, card number, city, and state in text format. However, within Microsoft Dynamics 365, I have a custom entity with fields for this information. When a user completes the webform and submits it, a ...

Verify the presence of values in several textarea fields with jQuery before executing a specified action

My main goal is to validate multiple dynamic forms on a single page. If all textareas are either empty or contain default values, I need a specific function to be executed. However, if any of the textareas have content that deviates from the default value, ...

Get the jsonarray file using express, node, and angular by downloading it

Within my web application, I am generating jsonarray files. These files have a structure similar to this: [{attr1:"123",attr2:"456"},{attr1:"abc",attr2:"def"}] I need to send these jsonarray files to the client for ...

The regular expression functions seamlessly on the Express Route Tester tool, but encountered errors when implemented in a NodeJS environment

I recently utilized Express in a NodeJs project and I needed to create specific routes for my server: /dogs /pinguin /bear /wolf /cat /rat To test these routes, I used a regex tool () : Express Route Tester While the express route tester showed everythin ...

Is it permissible to enclose useEffect hooks within an IIFE?

Currently, I am dealing with a project that is rife with anti-patterns. One issue that has caught my attention is the use of Immediately Invoked Function Expressions (IIFE) around multiple useEffect hooks. Here is a snippet of the code in question: conditi ...

Exploring Array Iteration: Navigating through Arrays with the .map Method in React and Vue

I am currently using Vue after coming from a React background. In React, there is a method called .map that allows you to render a component multiple times based on the number of items in an array and extract data from each index. Here's an example: f ...