Constructing a JSON schema for a dynamic aggregate query

Looking to create a query that matches fields with data in them.

Here is an attempt:

var matchStr = {};
if (received.user) {
    matchStr = { "_id":   { "$regex": received.user,  "$options": "i" } };
}
if (received.name) {
    matchStr += { "name":   { "$regex": received.name,  "$options": "i" } };
}
if (received.phone) {
    matchStr += { "phone":   { "$regex": received.phone,  "$options": "i" } };
}

usersTable.aggregate([
{
    $match: { matchStr }
}, etc...   

I also tried this:

var matchStr = [];
if (received.user) {
    matchStr.push( { "_id":   { "$regex": received.user,  "$options": "i" } } );
}
if (received.name) {
    matchStr.push( { "name":   { "$regex": received.name,  "$options": "i" } } );
}
if (received.phone) {
    matchStr.push( { "phone":   { "$regex": received.phone,  "$options": "i" } } );
}       

usersTable.aggregate([
{
    $match: { matchStr }
}, etc...   

Unfortunately, neither of these methods worked as intended.

Is there a more clever approach to achieve this?

Answer №1

A best practice is to avoid using an array in the $match function. Instead, consider using an object and assigning values to it like so:

let matchObject = {};
if (received.user) {
    matchObject["_id"] = { "$regex": received.user,  "$options": "i" };
}
//continue with other conditions

usersTable.aggregate([
{
   $match: matchObject
},
//more operations here...

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

Interactive JavaScript Slider for Customizing Selection

Recently, I came across a range slider and I am trying to make it more dynamic. The current JavaScript code has hardcoded references to specific HTML elements, and I want to have multiple sliders on my HTML page, each functioning independently. The code sn ...

"Using PHP, generate a JSON object containing an array named 'array' as one

I'm currently working on generating a JSON-String that has a specific format: {"id":"1","name":"new group test","beschreibung":"this is a description","gewerbe":"1" , "members":[{"uniqueid":"100110001"},{"uniqueid":"100110002"},{"uniqueid":"100110003 ...

Improving the Performance of DisplayField Binding in ExtJS 5

When I trigger a window to create a new item, there is a noticeable lag when passing in the record for the bound fields. The record is essentially a blank one with default values provided by the framework. In this demo, there are 3 buttons: The first but ...

Creating a counter while iterating over a JSON array in jq

I am currently working with jq-1.5. My goal is to generate a running counter (index) for a JSON array. The JSON data I have is: {"Actors": "Tom,Dick,Mary"} To split the string into an array, I am using splits(): echo '{"Actors": "Tom,Dick,Mary"}&a ...

Obtaining the result from within the .then() block

Through the utilization of Google's API, I am successful in retrieving and displaying nearby places on the console. router.get('/', function (req, res, next) { // Locating nearby establishments googleMapsClient.placesNearby({ ...

When reference variables are utilized before being parsed, what happens?

I'm a beginner learning Angular and have a question regarding the use of reference variables. Here is an example code snippet: <div class="bg-info text-white p-2"> Selected Product: {{product.value || '(None)'}} </div> <di ...

Is it possible to have a div automatically scroll when hovered over, while also hiding the scroll bar specifically for that div?

Is there a way to autoscroll a specific element onmouseover or via an image map while also hiding the scrollbars for that div? I seem to be struggling with this task despite weeks of learning javascript and not being able to find the right solution online. ...

"Utilize the Image ID to Showcase Images in a MEAN Stack

I am currently working on saving an image in mongoDB and then retrieving it to display from the Angular side. profile.html <input class="file-hide" type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." /> <button type="b ...

loop through a multidimensional array using a foreach

I am attempting to display an array in the following format: durations&quot;:[{&quot;months&quot;:&quot;36&quot;},{&quot;months&quot;:&quot;48&quot;}],&quot;duration_default&quot;:&quot;60&quot;,&quot ...

What is the process for creating an HTML file that can automatically save?

I am looking to develop a unique HTML document where users can enter text in text fields, save the file by clicking a button, and ensure that their changes are not lost. It's like what wysiwyg does for HTML documents, but I need it to be integrated di ...

Using Typescript to Import One Namespace into Another Namespace

Is it possible to export a namespace from one typescript .d.ts file and then import that namespace into another .d.ts file where it is utilized inside of a namespace? For instance: namespace_export.d.ts export namespace Foo { interface foo { ...

Is it possible to replicate keystrokes using Selenium in a CodeMirror text editor?

There are numerous illustrations available that demonstrate how to input text using selenium by utilizing the following code: driver.execute_script('cm.setValue("text")'); While this method works, it does not align with the standard practices o ...

Surprising Behavior of React's OnClick Event

Custom Component function ProductCard ({image, name, stats, id}){ let dispatch = useDispatch() let quantity = 1 return ( <> <div className="product-card" ...

NodeJS assert.AssertionError: How can I eliminate this error?

For my school project, I decided to create a web service using IBM Bluemix. However, I encountered an "assert.AssertionError" when attempting to run the code with "npm start" in the Windows 10 Command Prompt on my localhost. Can someone help me understan ...

Real-time database logging triggered by Firebase user authentication

exports.setupDefaultPullups = functions.auth.user() .onCreate( async (user) => { const dbRef= functions.database.ref; let vl= await (dbRef.once('value').then( (snapshot) => { return snapsh ...

Blurred entities aligning in front of one another (THREE.JS)

While experimenting with three.js, I encountered an issue with objects appearing fuzzy when they overlap. The distortion looks like this. Can anyone provide assistance with this problem? Below is the code I'm currently using: // Initializing basic o ...

Discover how to use your own search engine suggestions within the search bar of Google Chrome

I recently created a search engine on my website, and everything seems to be working perfectly when I visit the search page. However, I wanted to streamline the process by searching directly from the search box in Chrome. After adjusting the settings to ...

Is there a way to successfully implement mouseover/mouseout functionalities while also resizing?

I've been working on a dropdown menu that functions well on both mobile and desktop devices. However, I have encountered an issue with resizing. Even when the screen size is reduced to mobile dimensions, the mouseover and mouseout functions continue t ...

Having trouble with Laravel 5.5 and ajax file uploads?

I am encountering an issue with Laravel 5.5 while trying to get an ajax file. I can successfully receive the file using $_FILES, but $request->file() is not working as expected. Here is the code in question. Below are the HTML & Ajax elements: <htm ...

Execute a function for every parameter in the query string

My query string is designed as follows: dinnerPlate=white&lunchPlate=purple&cup=black In addition, I have an array that stores all of the permissible colors.. $availableColors = array("white","black","red","blue","green","pink"); The task at ha ...