Generate a custom query using user inputs

Let's say I am conducting a search in the database:

router.post('/searchLoads', ensureAuthenticated, async (req, res) => {
var{ agentCode, loadNumber, pickupNumber, pickupDate } = req.body});

The user does not have to complete all fields. How can I construct a query using if statements? I attempted something like this:

result = 'await Load.find({';
    if (agentCode !== undefined){
        result += "agentCode: agentCode, ";
    }
    if(loadNumber !== undefined){
        result += "loadNumber: loadNumber, ";
    }
    if(pickupNumber !== undefined){
        result += "pickupNumber: pickupNumber, ";
    }
    if(pickupDate !== undefined){
        result += "pickupDate: pickupDate, ";
    }
    result += "})";

After creating the query, I'm unsure how to execute the code. Is there a simpler way to accomplish this?

Answer №1

Instead of making a string, consider creating an object instead.

If we are working with ES6 or newer, we can use agentCode in place of agentCode: agentCode when setting up fields.

var options = {
    agentCode,
    loadNumber,
    pickupNumber,
    pickupDate,
};

result = await Load.find(options);

The need for !== undefined checks is eliminated, as any undefined fields will be automatically discarded.

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

What is the best way to add a dynamic parameter to the URL?

Here is an example of my URL: https://my-website.com/api/players?countryId=1&clubId=2&playerName=abc The parameter values can vary. This is the code snippet I use: getDataPlayer(payload) { let params if(payload.countryId && payl ...

Steps for sending data to a modal window

Consider this scenario: I have a function that retrieves some ids, and I utilize the following code to delete the corresponding posts: onClick={() => { Delete(idvalue[i]) }} Nevertheless, I am in need of a modal confirmation before proceeding with the ...

The camera steadily advances in WebVR Cardboard using three.js technology, never stopping its forward movement

I've been experimenting with trying to create a smooth, continuous forward movement for the camera in a three.js/WebVR project, specifically with only a cardboard viewer needed. After much trial and error, I've discovered that the usual camera m ...

Retrieving PHP form values using JQuery

How can I transfer a form input value from a PHP file to a JavaScript file? Here is the code I am currently using: <html> <head> <meta charset = "UTF-8"> <title> Search Customer by Field </title> <s ...

JavaScript Class experiencing issues with returning NAN when using the Multiplication method

Currently, I have a JavaScript Class with a multiplication method that aims to multiply all elements of an array excluding those that are undefined. To achieve this, I utilized a for loop to check the data type of each element (ensuring it is a number) and ...

Having trouble making axios a global instance in my Vue project

Previously, I used to import axios in each Vue component separately when making HTTP requests. An example of this can be seen below: <script lang="ts"> import axios from 'axios'; @Component export default class ExamplePage extend ...

Tips on positioning content beneath a fixed header or navigation bar when viewed in a web browser

Hi, I'm having an issue with creating a fixed header using HTML and CSS. When I set my header to be in a fixed position, it covers up the content below it. I want the content to be positioned under the header when the page is loaded. Additionally, I&a ...

Uncover the structure of a regular expression pattern to discover the quantity of tokens and the size of the anticipated matches

I am looking to validate certain fields in my forms by determining the number of tokens and length specified by a particular regular expression. For example, For the pattern [0-9]{3},[0-9]{2}, I need to identify 5 as the length and 2 as the number of to ...

Slice or eliminate the PlaneGeometry using XY coordinates

Just starting out in learning Three.js and looking to achieve the following: const customPlaneGeometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); if(customPlaneGeometry.x > 2 && customPlaneGeometr ...

What methods can be used to manage keyup events?

After following a tutorial for my class project on creating a 'frogger-like' game, I encountered a challenge with implementing player movement using arrow keys. The event listener provided in the tutorial facilitated this movement: document.addE ...

Automatically clear select2 inputs after form submission in Laravel using Livewire

How can I set my barcode scanner to automatically select and clear the search box upon submission? <script> $(document).ready(function() { $('.js-example-basic-single1').select2(); $('.js-example-basic-single1&ap ...

What is the best way to asynchronously load an external javascript file in a popup.html file?

I have successfully implemented all the necessary functionalities, but I noticed a delay in loading the popup.html after adding an external javascript file. This file is only a few lines long, so the delay is quite frustrating. To eliminate this lag, I be ...

What is the best way to deploy a user interface update to a JavaScript frontend?

I am in the process of creating a basic react application that fetches multiple images and presents them as cards. The goal is to have an informational message displayed while the images are being loaded, and then remove the message once all the images ha ...

Converting Database Information to JSON Format for Mobile Authentication Form

Currently, I am working on a Mobile App project using Phonegap that requires users to log in before retrieving JSON data. This PHP page is responsible for connecting to the mobile site and fetching the necessary information. <?php $con = mysqli_connec ...

Encountered a login issue when attempting to access the localStorage

Any suggestions on resolving this error? Encountering a QuotaExceededError with DOM Exception 22 This issue arises when attempting to access the localStorage and assign data to the header. Currently working with Angular 2 on the client side using Type ...

Visit localhost:3000 to view the contents of localhost/myproject/index.html

Recently, I ventured into the world of node.js with the intention of grasping how to access the node.js port (3000) by simply typing the URL of the index.html. Following the steps outlined in this tutorial to build a chat application, I encountered an issu ...

In React, the entire component refreshes every time the modal is opened

<ThemeProvider theme={theme}> <GlobalStyle /> {componentName !== 'questionaire' && componentName !== 'activityResult' && <CardWrapper />} <ErrorModal ...

Which is better for a jQuery/Ajax Login Box: JSONP or CORS?

To create a login box that meets the specified criteria, the following must be taken into consideration: Develop it as a versatile UI Component that can be utilized in various sections of a website Allow for multiple instances of this component to coexis ...

What is the best way to reset a CSS background GIF after hovering over it?

Is there a way to create a texture animation with text using CSS background GIFs that reload when hovered again? I've tried some JavaScript/jQuery but can't seem to make it work. Any suggestions? I attempted the following approach, but it's ...

Using a minus sign to denote negative values and leading zeroes to indicate positive values in regular expressions

I need help with a unique form validation requirement using regex. The values must be integers between -168 and 10688, where negative values range from -168 to -10688. What makes this challenging is that users must include leading zeros, with 4 character ...