What is the best way to omit a field from my query if the associated variable is empty?

I need help creating a dynamic MongoDB query function that can handle multiple field values, including cases where some fields may be empty strings. In these instances, I want MongoDB to disregard those parts of the query.

Here is my current query function:

function GetReports(args) {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, function (err, db) {
            if (err) throw err;
            var dbo = db.db(args.organization);
            dbo.collection("reports").find(
                {
                    "name": { 
                        $regex: "(?i)" + args.query + "(?-i)" 
                    }, 
                    "project_number": { 
                        $regex: "(?i)" + args.project_number + "(?-i)" 
                    }, 
                    "category": args.category
                }).sort( { "date_sent": -1 }).skip(fetchedDocPerCall * (page - 1)).limit(fetchedDocPerCall).toArray(function (err, result) {
                if (err) reject(err);
                db.close();
                resolve(result);
            });
        });
    });
}

In this function, I aim to retrieve documents based on matching the regex pattern of either the "name" or "project_number" fields, while ensuring an exact match for the "category" field. The challenge lies in handling scenarios where some arguments passed to the function are empty strings. Instead of searching for documents with empty string fields, I want MongoDB to skip those parts of the query. Although I could create numerous functions for each possible combination, I am hoping to streamline this into a single versatile query function.

Answer №1

After considering @Cris G's recommendation, your code could be structured as follows:

function FetchData(criteria) {
  return new Promise((resolve, reject) => {
    Database.connect(databaseURL, function (error, connection) {
      if (error) throw error;
      var databaseInstance = connection.db(criteria.organization);
      const fieldMapping = {
        searchField: "name",
        projectNumber: false,
        categoryType: false,
      };
      const queryCriteria = {};
      for (const [key, value] of Object.entries(fieldMapping)) {
        if (key in criteria && criteria[key] !== "") {
          Object.assign(queryCriteria, {
            [value || key]: criteria[key],
          });
        }
      }
      databaseInstance
        .collection("data_entries")
        .find(queryCriteria)
        .sort({ sentDate: -1 })
        .skip(recordsPerPage * (currentPage - 1))
        .limit(recordsPerPage)
        .toArray(function (error, retrievedData) {
          if (error) reject(error);
          connection.close();
          resolve(retrievedData);
        });
    });
  });
}

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

The function getComputedStyle(elem).getPropertyValue('fontSize') returns incorrect values when the font size of the element is specified in em units

My current issue involves trying to obtain the font size of an element in the following manner: getComputedStyle(MyTargetElement , "").getPropertyValue('font-size') The result is coming back as 16px, when it should actually be 14px. W ...

Leverage AngularJS to effectively parse JSON data using scope variables

I am trying to JSON parsing in AngularJS using $stateParams in the controller below: rerunApp.controller('rerunCategoryListCtrl', function($scope, $http, $stateParams) { var stpNameCat = $stateParams.nameCat; $http.get(JSON UR ...

The error message appeared as a result of the bluebird and mongoose combination: TypeError: .create(...).then(...).nodeify is

Recently, I encountered an issue while attempting to integrate bluebird with mongoose. Here's the scenario: I wrote some test code using bluebird without incorporating mongoose, and it worked perfectly. The code looked something like this: A().then( ...

Issue: The system is unable to locate the module labeled './lib/binding/napi-v3/argon2.node'

After attempting to install bcrypt or argon2 with the command npm install --ignore-scripts --omit=dev, an error occurred: app-1 | node:internal/modules/cjs/loader:998 app-1 | throw err; app-1 | ^ app-1 | app-1 | Error: Cannot find modul ...

Summernote information embedded with HTML elements

I just started using the summernote text editor and I'm trying to figure out how to extract the content from the textarea without all the HTML tags. This is what I have in my code: <textarea class="summernote" id="summernote" ng-model="blog.c ...

Is there a way to efficiently send multiple files in nodejs using mongodb?

When querying my database to filter articles by date, the user inputs a date and the server retrieves the list of article IDs written by the user. The server then checks the article collection for these IDs and compares the requested date with the 'cr ...

What could be causing my Vue component to not refresh?

Can anyone help me figure out why this component isn't re-rendering after changing the value? I'm attempting to create a dynamic filter similar to Amazon using only checkboxes. Here are the 4 components I have: App.vue, test-filter.vue, filtersIn ...

No matter how hard I try, the async function within the React Component keeps returning 'Promise {<pending>}' consistently

Currently, I'm facing an issue where running an asynchronous function inside a functional component in React (NextJS) results in the function returning a pending promise: Promise {<pending>}. Oddly enough, fetching data from a dummy API works pe ...

What is the best method to remove a value from a JSON object in a CSV file?

I received a JSON response like this: xxx: ["fsd,das"] I am looking for a way to remove the value "fsd" from the JSON object. The issue is that the response inside the JSON is not actually an array, but rather a CSV format. How can I go about deleting it ...

Maximizing the use of JavaScript's prototype.js library: Passing parameters to callback functions

My understanding of JavaScript is limited to using it for Dynamic HTML. However, I am now exploring Ajax and facing an issue with the code below (taken from and modified to suit my requirements). I need to pass the update_id parameter to the onSubmit fun ...

What is the best way to navigate through an XML document within the DOM of an HTML

I am facing an issue with HTML code. My goal is to navigate through an XML document directly from within the HTML code. Here is the XML code: <?xml version = "1.0"?> <planner> <year value = "2000"> <date month = "7" day = " ...

Listening for key combinations in VueJS using a mounted event listener

I am facing an issue with my global key listener - it only catches single key strokes. How can I modify it to capture combinations like ctrl+enter? mounted() { window.addEventListener ( "keypress", e => { console.log ...

TypeScript interface with an optional parameter that is treated as a required parameter

Within my interface, I have a property that can be optional. In the constructor, I set default values for this property, which are then overridden by values passed in as the first parameter. If no properties are set, the defaults are used. I am looking fo ...

Unlike other templating engines, EJS does not automatically escape characters

In my current project, I am utilizing a Node JS server to query MongoDB and then display the results in an EJS template using the code snippet: res.render('graphFabric.ejs', {'iBeacons':[(beacon)]});. However, when attempting to re ...

Creating a process to automatically generate an input field upon the selection of checkboxes

Is there a way to automatically generate a text field for each checked box in a dynamically changing checkbox list? Below is my code snippet: <div> <label> Products </label> <li ng-repeat="item in INDproducttypes"> ...

Is there a way to have a button function as a submit button for a form even when it is located in a separate component within a react application?

I am in the process of creating a user-friendly "My Account" page using react, where users can easily update their account information. I have divided my components into two sections: the navbar and the form itself. However, I am facing an issue with the s ...

Looking to display a page header alongside an image on the same page

I'm currently learning React.js and working on my very first app. As someone new to frontend development, I am aiming to have a header design similar to that of popular websites like StackOverflow or YouTube, where an image or icon is positioned just ...

Execute various settimeout or display functions on various elements of a webpage

Just a heads up, I'm not really experienced in development. More on the newbie side of things, but eager to learn. I've been looking for an answer to my question, but so far haven't come across anything that fits my specific situation. It m ...

Troubleshooting a Vue.js formatting problem in Visual Studio 2019

Encountering an issue with VS2019 while attempting to format this code section. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="milestone.ascx.cs" Inherits="uc.dms.milestone" %> <section class="content-header"> <h1> ...

Ways to efficiently update styles dynamically using css and/or javascript

I am trying to update the styles of a button when it is clicked. I initially set the style for the first element on page load, but now I need to remove those styles from the first element and apply them to the clicked button instead. I am having trouble fi ...