Utilizing multiple conditions in MongoDB is a great way to filter results when a specific key

const filterCriteria = {
        carColor: req.query.carColor, 
        languages: { $regex: `${req.query.languages}`, $options: 'i' },
        incomeMonth: { $gte: req.query.incomeMonth },
        incomeYear: { $gte: req.query.incomeYear },
        age: { $gte: query.fromAge, $lt: query.toAge }, // age from - to
        familyStatus: query.familyStatus
    }

    const filteredProfiles = await Profile.find(filterCriteria)
        .sort({ createdAt: 1 })
        .limit(100)

    return res.json({ success: true, count: filteredProfiles?.length, profiles: filteredProfiles })

For instance, if I have multiple queries and one of them is related to language with the key req.query.language. I only want to apply the $regex method for this specific query key. If any query key is empty, I prefer not to include it in the find() method.

Answer №1

Make sure to populate the filterOptions object only for existing keys.

let filterOptions = {};
if (req.query.carColor) {
  filterOptions =  {...filterOptions, carColor: req.query.carColor};
} 
if (req.query.languages) {
  filterOptions =  {...filterOptions, languages: { $regex: `${req.query.languages}`, $options: 'i' }};
}
if (req.query.incomeMonth) {
  filterOptions =  {...filterOptions, incomeMonth: { $gte: req.query.incomeMonth }};
}
if (req.query.incomeYear) {
  filterOptions =  {...filterOptions, incomeYear: { $gte: req.query.incomeYear }};
}
if (req.query.fromAge && req.query.toAge) {
  filterOptions =  {...filterOptions, age: { $gte: query.fromAge, $lt: query.toAge }};
}
if (req.query.filmStatus) {
  filterOptions =  {...filterOptions, familyStatus: query.familyStatus};
}

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

Animating slides with CSS Keyframes and React, incorporating toggle slide fade out and slide fade (back) in

I am seeking a solution for toggling a box (div) with slide-out animation and then sliding back in animation (in reverse) upon button press. My requirement is to have no animations during the initial page render. While I can successfully slide the box to ...

Position the typography component to the right side

Is there a way to align two typography components on the same line, with one aligned to the left and the other to the right? I'm currently using this code but the components are aligned next to each other on the left side. const customStyles = makeSt ...

Safari browser cutting off POST parameters prematurely

I am encountering an issue where my code works perfectly on all browsers except Safari 6.1.2 on Mac OS Lion. Below is the AJAX post code that I am using - $.ajax({ type: 'POST', dataType: 'text/html', url:"/MyProxy.php ...

Looking for assistance with reviewing and optimizing Angular UI-Router implementation

I'm currently facing an issue with setting up routing for my angular portfolio. Despite checking my code against a previous app, I am unable to identify the error as there are no console logs when I compile. Can someone please review my code layout an ...

What is the best way to display text from a file on a different html page using jQuery's json2html?

Here is the json data: var data = [ { "name": "wiredep", "version": "4.0.0", "link": "https://github.com/taptapship/wiredep", "lice ...

What is a reliable method for consistently updating backend C# with user-side JS data whenever it is altered?

I'm working on a front end JS application that includes visual sliders. I need to send the updated slider information to the C# backend (ASP.NET) whenever a user makes changes. After some research, it seems like AJAX is the most efficient way to achie ...

A website utilizing single-page architecture and HTML navigation through servlet technology, all without the need to open additional pages

I am interested in downloading files using a servlet when a link is clicked. My website is built using single page architecture in HTML. How can I trigger a servlet without changing the page when a link is clicked? I have been attempting to achieve this ...

Three.js experiencing issues with its Raycaster functionality

Currently, I'm working on a game where players navigate in a first-person view over dynamically generated uneven terrain using Perlin noise. To make the experience more realistic, I aim to incorporate gravity into the gameplay. For this purpose, I&apo ...

The filter function in JavaScript's Array is malfunctioning on Internet Explorer version 7

My web application includes a jQuery plugin that is functioning correctly in Internet Explorer 10 and 11. However, it is not working in IE 7. Upon investigation, I discovered that the value of the filter method is showing as undefined. The line of code th ...

Jquery Position behaving unexpectedly during initial invocation

My goal is to have the autocomplete menu open above the input box if there is not enough space below it. The code functions properly, except for the initial render. It consistently displays at the bottom in the following scenarios: 1. When starting a searc ...

Is there a way to switch tabs through programming?

Is there a way to switch between tabs using jQuery or JavaScript when using the tabbed content from ? I have tried using $("tab1").click(); I have created a fiddle for this specific issue which can be found at: https://jsfiddle.net/6e3y9663/1/ ...

An anchor-shaped name tag with a touch of flair

I stumbled upon this unique anchor name design on the website Does anyone here know how to create something similar? What is that style called? ...

Animating meshes in Three.js with texture mapping

After conducting some research, I successfully exported an obj file to a .js file that can be imported by the JSON model of Three.js. However, I am now faced with the challenge of animating this model. Specifically, I have a bird model in .js format that I ...

A guide to sending props to a CSS class in Vue 3

I need to develop a custom toast component that includes a personalized message and class. While I have successfully passed the message as props, I am encountering difficulties in applying the bootstrap class. Component File: Toast.vue <script ...

Unable to utilize ES6 syntax for injecting a service

I am encountering some issues while trying to implement a service into a controller using ES6 syntax. CategoriesService.js export default class CategoriesService { constructor() { this.getCategories = function ($q) { var deferred ...

The outcome of the JQuery function did not meet the anticipated result

Here is the code I am using: $("p").css("background-color", "yellow"); alert( $("p").css("background-color")); The alert is showing undefined instead of the expected color value. I have tested this code on both Google Chrome and Firefox. Strangely, it w ...

What is the best way to change an asterisk symbol into 000 within a currency input

In my ASP.NET application, I have a currency text box. I have the following script: <script type="text/javascript> function Comma(Num) { //function to add commas to textboxes Num += ''; Num = Num.replace(',', ...

What is the best way to display loading details during a data loading process within a useEffect hook?

Whenever a specific custom React component I've created is initially mounted, it utilizes useEffect to initiate a lengthy multistep process of loading data that will later be rendered. Since the component isn't always rendered, this costly proces ...

Set the rowspan to 2 when the v-for index does not equal 2

This is the table I am working with: <table class="table table-condensed table-sm table-striped table-bordered" id="list"> <thead> <tr> <th v-for="(column, index) in columns" :key=& ...

Guide to adding table classes to AJAX response tables

I am facing an issue with displaying data in a table based on the AJAX request made. The problem arises because the data displayed does not follow the pagination classes applied to the table. My table has pagination functionality where 10 records are shown ...