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

Build a React application using Node and Express for importing images

I'm new to this and have been searching through different resources for guidance. I'm on a mission to discover the most effective approach. After following a tutorial that sets up the create-react-app boilerplate with a node express backend, eve ...

Prevent automatic scrolling to anchors when using router.push() in Next.js

When using the latest version 10.2 of next, every time a URL with a hash is pushed to the router, next.js automatically jumps to the anchor element. import {useRouter} from 'next/router' router.push('/contact#about-us'); This behavior ...

AngularJS: Recommendations for structuring code to dynamically update the DOM in response to AJAX requests

Within Angular's documentation, there is a straightforward example provided on their website: function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.order ...

Counting the number of key-value pairs for a specific key in a JSON data can be achieved by implementing

Is there a way to determine if __metadata and ItemToEkbeNav are the root elements for their children who have key-value pairs? I've attempted various methods such as Object.keys().length and Array.isArray(), but haven't been able to retrieve the ...

Is there a way to determine if a browser supports the offline event?

I attempted to implement the code from this Stack Overflow question: How can I check for support of the `focusin` event? However, in Chromium, the method hasEvent('offline') returns false even though it supports the `offline` event. Does anyone ...

Svelte Material UI Circular Progress Indicator encountering issues

I'm having trouble getting the Svelte Material UI Circular Progress indicator to function properly. I attempted to implement it in my project initially, and then decided to try it out in Code Sandbox using the provided code from the documentation. How ...

How can you preselect an item in Vuetify's item group?

When attempting to preselect an item from a vuetify item-group, I discovered that it works with strings but not with objects. The vuetify documentation shows using a string array as the item list for the item-group, which functions correctly. However, whe ...

Using Node.js to send a response only after every promise has been resolved

I am currently working on a NodeJS Express route where I have encountered an issue. In this route, a function is called multiple times, each returning a Promise. The values from these Promises are then added to an Array and sent back to the client using re ...

Toggle divs by using a checkbox (Vue.js)

On my authentication page, I have implemented a checkbox that I want to use to toggle between Sign Up and Sign In forms. When the checkbox is clicked, it should display the Sign Up form, and when it's unchecked, it should show the Sign In form. I fou ...

Utilizing nodejs to interact with a web service

Recently diving into Node.js and currently exploring how to utilize services with NodeJS. Seeking guidance on the NodeJS equivalent of the code snippet provided below: $.ajax({ type: "POST", url: "/WebServiceUtility.aspx/CustomOrderService", data: " ...

When using Node.js with Mongoose, you will receive a single object value instead of multiple values in an array

data=[{ locId: '332wn', locadetails: [ { loc: 'ny', status: true }, { loc: 'ca', status: null ...

Steps for retrieving a Unicode string from PHP using AJAX

In order to retrieve Unicode strings from PHP for my project, I figured that using AJAX would be the most suitable method. $.ajax({ url: './php_page.php', data: 'action=get_sum_of_records&code='+code, ...

Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I ...

JavaScript / Ajax / PHP - A Minor Bug That's Bugging Me

I'm in need of some help, as I feel like I'm losing my mind right now. I've developed a code using php/js/ajax to verify if an email address exists when it's submitted. After testing the ajax, I can confirm that the correct values are ...

Using buttons as spinners for input elements with identical styles but unique identifiers

Currently, I am in the process of developing a project that involves users. In order to display all users, I am executing a query on an SQL database. After styling the interface, I have added an input element beside each user, which initializes at zero. Ad ...

CKeditor does not accept special characters or diacritics in keywords

Recently, I came across a helpful code snippet for CKeditor that counts and ranks the most used words in a textarea. This feature is invaluable for generating SEO-keywords suggestions while writing articles. However, there is an issue with non-English char ...

Encountering problems with parsing a lengthy JSON file

Can you spot the issue here? let stringinsta = JSON.parse({ "access_token":"129261**5ea59a4da481c65", "user":{ "username":"carlos_bellesso", ...

Handling scroll events in a functional component using React

I'm having trouble understanding why the onScroll function isn't triggering the console.log statement. <table className="table" onScroll={()=>{console.log("Works")}> The console.log just doesn't seem to be exec ...

Using the JavaScript selectionchange event to target a specific element exclusively

I am looking for a way to incorporate a JavaScript selectionchange event on a specific div element. The goal is to display a highlighter box when the user selects text from the DOM. I was able to achieve this functionality for web using an onmouseup event, ...

loading user input triggers dynamically populated dropdown in react-select

Just getting started with React and experimenting with merging two different functionalities. One involves a dynamic form where inputs can be added or removed, while the other utilizes async react-select for filtering options based on an API source (like c ...