Narrow down product selection by multiple categories

I'm currently in the process of working with Express and MongoDB, where I have data items structured like the following:

{
  "_id": {
    "$oid": "63107332e573393f34cb4fc6"
  },
  "title": "Eiffel tower",
  "attractionType": [
    {"$oid": "63035678df60496a551a8138"},
    {"$oid": "63035678df60496a551a813d"},
    {"$oid": "63035678df60496a551a8142"},
    {"$oid": "63035678df60496a551a813e"}],

}

{
  "_id": {
    "$oid": "63107332e585673f54hj444"
  },
  "title": "Taj Mahal",
  "attractionType": [
    {"$oid": "63035678df60496ao6567p90"},
    {"$oid": "63035678567h496a551a66gr"},
    {"$oid": "63035678df60496a551a8138"},
    {"$oid": "63035678df60496a551a813d"}],

}

My current challenge involves filtering these items based on attractionType. When sending attraction types as queries to Rest API, the format is like this:

http://localhost:8000/app/heritages?attractions=63035678df60496a551a813

The above query works for a single value of attractionType, but I would like to understand how to handle multiple attraction types like this:

http://localhost:8000/app/heritages?attractions=63035678df6d6a51a8136,6303568df6049a551a8137

Below is my code snippet for handling one attraction type, I need help on extending it to handle more than one filter:


  var { attractions } = req.query;
  var lang = req.lang;
  var conditions = { lang: lang };

  if (attractions && attractions.length > 0) {
    conditions.attractionType = attractions;
  }

  try {
    Heritage.find()
      .where(conditions)
      .populate("provinceId attractionType")
      .sort(sortItem)
      .exec((err, doc) => {
        if (err) {
          return res.status(500).json({ message: "server Error", err });
        }
        return res.status(200).json({ message: "seccess", lists: doc });
      });
  } catch (e) {
    return res.status(500).json({ message: "server Error" });
  }
};

Answer №1

Try using this code snippet

http://localhost:8000/app/heritages?attractions[in]=63035678df60496a551a813
to potentially resolve the issue at hand.

Remember to include [in] before the specified value.

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

Differences Between Put and Post in Node.js

I am currently exploring NODEJS in conjunction with react. In a typical scenario, the request to edit posts would look like this: router.put("/:id", function(req, res) { Campground.findByIdAndUpdate(req.params.id, req.body.campground, function( e ...

How can we effectively reroute HTTP requests according to the information stored in a database?

When operating an express server, what is the appropriate method for redirecting incoming requests? In my application, I have two routes: POST and UPDATE. The POST route is responsible for creating a new item in the database, while the UPDATE route increa ...

Node.js AWS S3 Presigned URL with SignatureMismatch

I am currently working on a NodeJS script to reverse-proxy client requests by creating pre-signed URLs for S3 objects being requested. For instance, when a user accesses the website at build.localhost:8080, the 'build' subdomain corresponds to a ...

Rails: Ensure that JSON form fields remain populated in case the form encounters a validation error

I am using a rails simple form to create a product with three fields inside in order to associate it with appropriate categories: <div class="form-group"> <%= f.input :child_category_id, :collection => @categories.order(:name), :l ...

Using Selenium WebDriver to Extract Variables from JavaScript SourceCode

Currently, I am dealing with a web page source code that utilizes JavaScript to display text. Below is an excerpt from the source: var display_session = get_cookie("LastMRH_Session"); if(null != display_session) { document.getElementById("sessionDIV") ...

Navigating to the next page in Angular JS by clicking "Save and Next" which

Hey there, I'm currently diving into Angular JS and working on a CMS system with it. Right now, we're dealing with around 30 to 40 Objects that we load into a list. Whenever one of these objects is clicked, a Modal Window pops up using the Modal ...

Employing live labels on a Morris Bar Chart

I'm using the Morris Bar Chart to showcase the sales of different products. To enhance user experience, I want to display dynamic labels when hovering over the bars. The data is being fetched through PHP. array('product' => $row['pr ...

Having trouble accessing variables from the dotenv file in a NextJS project

Recently, I started using Next.js and ran into a bit of trouble. Here's the issue: When I'm in the connectToMongo function, my variable is coming through just fine. However, when I switch over to Main/index.tsx, my process.env appears as an emp ...

Having trouble establishing a connection between the client and server while using Node.js with socket.io, Express, and an HTML file

While following a tutorial on YouTube for creating a simple web game with lobbies/rooms, I encountered an issue. When attempting to establish a connection between the client and server, the expected "a user connected" text did not show up in the console as ...

I Tried Adding Up All the Numbers, but It Doesn't Seem to Work for Every Dynamic Total Field

In my project, I am utilizing Laravel 5.7 and VueJs 2.5.*. The issue I am facing is that when I input values, the Total field calculates correctly. However, when I dynamically add rows for items, the calculation only works for the first row and not for the ...

Steps to resolve eslint error in cases of using the node: protocol for importing Node.js built-in modules

Can someone guide me on what to include in my .eslintrc file for my specific situation? Link 1 Link 2 If I disable this rule, I encounter the following error: import path from "path"; // ESLint: Prefer `node:path` over `path`.(unicorn ...

Error message: A boolean type cannot be used as a function in the fullcalendar ajax call

I have successfully implemented a fullcalendar into my app and have added a method to filter results by user: function filterEventsByProvider(selected_provider) { $('#calendar').fullCalendar('removeEvents'); $('#calendar&a ...

How can I properly integrate multer with Node and Express in this situation?

I've been working on setting up a route for uploading photos, but after making some changes, it has stopped functioning and I'm not sure how to fix it. const multer = require('multer'); // MULTER STORAGE const multerStorage = multer.di ...

How can JavaScript be properly embedded using PhantomJS?

My objective is to insert the following code snippet into a website using PhantomJS: javascript document.getElementById("pickupZip").value = "90049"; document.getElementById("refreshStoresForZipPop").click(); After attempting this in my inject.js file, I ...

Import and load numerous JSON files into a responsive and visually appealing Bootstrap table

I am new to coding in javascript and I'm seeking assistance in loading multiple JSON files to populate a bootstrap table. Currently, I've managed to create a table by manually combining the content from different files into one variable called l ...

directive still running despite attempting to stop the service

In my modal window, there is a directive that utilizes a service to make HTTP requests at regular intervals using $interval. However, even after closing the modal window, the service continues to run and make requests every 30 seconds. Is there a way to ...

Aligning the 'container-fluid' slideshow and video player

I'm struggling to center a video in a slick slider that is set as a 'container-fluid'. The slideshow and video display fine across the full width of the browser, but when I resize the browser window or view the site on a lower resolution, I ...

What is the best way to display a div beneath the highlighted text within a textarea field?

I have encountered a situation where I want to display a div (like a popup) when text is selected in a text area. However, when using mouse-down for this action, the position of the div sometimes does not align directly below the selected text. Below is t ...

I possess a collection of server-side questions and answers. How can I display them one by one in an EJS template upon clicking?

Here is the path I have chosen: app.get('/test', (req,res)=>{ res.render('index.ejs',{qData: [{Q1},{Q2},...]}); }) Is there a way to display this qData sequentially on the client side with each click? Imagine I have two buttons la ...

Creating a multi-tiered RESTful API using Node.js and Express

Currently, I am utilizing node.js express for constructing a straightforward rest API. I have already created an API like this: app.get('/sites/:site/:building/:floor',function(req,res){ var building = req.params.building, floor = req.params ...