Search in MongoDB for documents where multiple conditions are met simultaneously

Is it possible to use $and in combination with some dynamic values when using the find method?

For example:

let { city, zanr, date } = req.body;

const selectedEvent = await Events.find({
  $and: [{ address: city}, { type: zanr }, { date: datum }],
});

In some cases, the value "all" might be present in req.body, indicating that no filtering is needed.

Occasionally, the address field may need to be set to "any".

Answer №1

In the case where city is entirely removed, delete {address:city} from the and array or substitute it with {address:{$regex:'.*.'}}

 let { city, genre, date } = req.body;

    const selectedEvent = await Events.find({
      $and: [ {address:{$regex:'.*.'}},{ type: genre }, { date: datum }],
    });

Answer №2

Using javascript, you have the ability to dynamically create queries based on the data in req.body.
These queries in MQL format are essentially JSON objects that can be generated and modified as needed.

Here is an example:

var q;

if(city=="all") q=[{ type: zanr }, { date: datum }];
else q=[{ address: city}, { type: zanr }, { date: datum }];

const selectedEvent= await Events.find({$and: q});

If you have additional filters besides the city, you can apply the same dynamic query generation logic for those as well.

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

Ways to update Title label's CSS using JavaScript

These are my CSS rules: label[title="Hot"]{ display:none; } label[title="Cold"]{ display:none; } I am looking to convert this into JavaScript. Can you assist me with that? ...

Struggling to Traverse a nested object in a node.js environment

I've been attempting to iterate over a nested object and save the data to my cloud firestore database, but unfortunately it's not working as expected. Below is the structure of the object retrieved from an API call: { "count": 133, ...

Unveiling an HTML file using the express.static middleware on Replit

When using Replit to render an HTML file with res.sendFile within an app.get function, everything works smoothly. I can include logos, styles, and JavaScript logic files by utilizing the express.static middleware. However, if I attempt to also make the HTM ...

Tips for implementing a 2-second delay in Ajax success function

I am experiencing fast responses when fetching data in each loop, but I need to introduce a delay. I have tried using setTimeout and delay methods without success. I believe there might be a different approach that I should consider, but I am unsure how ...

Is there a way for me to dynamically retrieve the properties of an object in TypeScript?

My form has multiple fields for data input: <input type="text" placeholder={`title`} onChange={(e) => updateField(`title`, e)} /> <input type="text" placeholder={`description`} onChange={(e) => upd ...

The art of bringing a pseudo class to life through animation

Seeking assistance with achieving a unique effect on click event. I have set up a slanted or razor-blade style div using a parent div element and a pseudo-element :after (as shown below). My goal is to change the skew angle when the user clicks on the pare ...

Utilizing a single component to display an assortment of values

With the following code, I initially hard coded 4 sections: "general welfare," "travel guide," "medical guide," and "rental guide" to the card by duplicating the same card component in return. Now, I am using a category array to store these four elements ...

Configuring unique capabilities for the Selenium WebDriver

My goal is to customize the settings of a Selenium Webdriver. In this particular case, I am looking to modify a capability of the webdriver specifically for the Firefox browser. All of this needs to be done using Javascript. this.driver = new selenium.Bu ...

Encountering a problem when trying to reference socket.io

I've been working on building an express app with chat functionality, but I've run into an issue with socket.io. It's not working properly and is throwing an "uncaught reference" error when I try to run the server. You can see a screenshot o ...

Navigating through relationships in BreezeMongo: Tips and tricks

In my current setup, I have defined two entities: Hospital and Patient with a one-to-many relationship. The metadata for these entities is created as follows: function addHospital() { addType({ name: 'Hospital', ...

What are the methods to manage rate limiting in Next.js 14?

I have recently started working with Next Js 14 and Mongo DB. While using Node Js, I learned about the Express Rate Limit package which allows for controlling the number of requests made by website users. If a user exceeds 200 requests in a span of 15 min ...

Unable to invoke setState (or forceUpdate) on a component that has been unmounted

After updating the component, I encountered an issue with fetching data from the server. It seems that componentWillUnmount is not helpful in my case since I don't need to destroy the component. Does anyone have a solution for this? And when should I ...

What could be the reason for the view/Vue.js dev tools not updating with the new data after pushing an item into a data array?

Despite pushing data into an array, the view and Vue dev tools do not update. Why is this happening? Even after clearing the browser cache, the issue persists. myData = [ [ { test: true } ] ] methods: { addDataItem() { ...

Using several autocomplete-light dropdown menus in a Django template

I am in the process of creating a web application that necessitates searching for a specific user record by inputting either the first name OR last name. While two more search attributes will be added in the future, I am currently facing issues with incorp ...

Build a brand new root component in Vue JS

I am facing a challenge with destroying and re-creating the root application component. Below is my template structure: <div id="app"> {{ num }} </div> Here is the code I have implemented: if (app) { app.$destroy(); } else { ...

Issue with Django link not functioning properly within a for loop

My attempt to enclose a piece of table data in an HTML table with a link seems to be resulting in some unexpected behavior when viewed in Chrome's Element Viewer. <a href="/tasks/1/"></a> <a href="/tasks/2/"></a> <a href="/ ...

Unable to define attributes of a non-existent element (specifically 'innerHTML') within a Vanilla JavaScript component

Currently, I'm developing a Vanilla JS Component and encountering a challenge with utilizing the innerHTML() function to modify the text within a specific ID in the render() HTML code. The problem at hand is the Cannot set properties of null (setting ...

An image's dimensions must be verified before assessing its criteria

In my project, I am facing a challenge with image uploading functionality. The requirement is to check if the uploaded image exceeds the maximum criteria set. If it does, an alert message should be displayed. alert("Height exceeds our maximum criteria. Pl ...

Guide to converting an arraylist of custom objects into JSON using JavaScript

I have a List returned to the jag. It is of type (java.util.List) and I need to print it as a json. var storeForum = Packages.org.wso2.carbon.forum.registry.RegistryForumManager; var forum = new storeForum(); var start = request.getParameter(&a ...

Jquery function for determining height across multiple browsers

I am currently facing an issue with setting the height of table cells in my project. While everything works smoothly on most browsers, Firefox seems to add borders to the overall height which is causing inconsistency across different browsers. If anyone k ...