Using an array of objects to apply Regex filtering in MongoDB and Mongoose

I am working on creating a dynamic filter that can be used with just 3 letters. I have multiple fields that need to be filtered.

For instance, when searching for users by email, I want to be able to type "@gma" or "gma" and get back an array of all users matching the filter value. The same functionality should apply when filtering by properties like firstName.

Currently, my solution only works if I provide an exact match from the database, such as

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a7b6a0a793b4beb2babffdb0bcbe">[email protected]</a>
for email or "john" for firstName. I want to be able to search for "jo" and still get results for firstName.

const regexPattern = new RegExp(["^", filterUsersByValue, "$"].join(""), "i");
const filteredU = UserModel.find({ [filterUsersBy]: regexPattern})

Answer №1

It seems that using JS allows you to create the find object in a certain way:

let queryObject = {}
queryObject[searchKey] = {$regex:searchTerm, $options:"i"}
const results = DatabaseModel.find(queryObject)

This method generates the following object:

const searchTerm = "abc"
const searchKey = "name"
let queryObject = {}
queryObject[searchKey] = {$regex:searchTerm,$options:"i"}
console.log(queryObject)

This is similar to what is shown in this example query

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

Prevent dropzone from refreshing the page

For the past few days, I have been scouring the internet for solutions on how to prevent a page from automatically reloading after an upload. Despite finding various methods, I have been unsuccessful in resolving this issue. Although I am following the st ...

Remain on the React page following an HTTP POST request to Flask

Is there a way to stay on the React frontend (localhost 3000) after completing a POST request to a Flask backend from a React form, without redirecting in the Flask backend? Relevant code: export const DateForm = () => { return ( <div&g ...

Image can be centered, but unable to center div in IE7

When trying to center an element both vertically and horizontally, everything seems to be working correctly except for one issue I'm facing in IE7. I am able to center an img vertically but not a div. What style is being applied by IE to the image tha ...

Display the name of the link on the console

I am working on an HTML list that contains some links: <ul> <li><a href="#" name="link1">link1</a></li> <li><a href="#" name="link2">link2</a></li> <li><a href="#" name="link3">link3& ...

Tips for storing Ajax request information into separate variables

Seeking a way to store data returned from an ajax call into separate variables. Ajax Call $.ajax({ url: 'fetch_lat_lng.php', type: 'GET', dataType: "html", success: function(data) { //executed on successful response ...

The createReadStream function cannot be found in the uploaded image

I am currently using node v14.17.0, "apollo-server-express": "^2.25.0", "graphql-upload": "^12.0.0" I'm facing an issue with uploading an image as I don't receive the createReadStream from the image that I upload via graphiql. Specifically, I am ...

The JQuery click handler seems to only be functioning on the initial item

I am currently working on a table where I need to create a functionality that can change a value in the database for each row. However, I am facing an issue where the changes I make only affect the specific row in the table and not the rest of the rows. M ...

Executing an xajax/ javascript function simultaneously

Is there a way to simultaneously execute the same function? Here is an example: function convert_points() { show_loading(); xajax_ConvertPoints(); xajax_GetRegularGamingCards(); } When xajax_ConvertPoints is called, there seems to be a mill ...

Using the parseInt method, you can easily combine integers and strings to perform addition and string concatenation simultaneously

Here is the code snippet I am working with: if (ev.data.type === "height") { if (ev.data.form === src) { setHeight(ev.data.message + "px"); } } Currently, the default height being added is 1900px. I would like to increase it by ...

Having trouble with AngularJS and NodeJS routing integration?

After deciding to dive into the world of application development using the MEAN Stack, I encountered a major roadblock. For the past hour, I've been struggling to set up a basic route, only to face failure at every turn. Whenever I try to access my ...

THREE.js : Chart Your Course in the Digital Realm

When I have a moving object controlled by code such as: dx = [not important]; dy = [not important]; dz = [not important]; d = new THREE.Vector3(dx, dy, dz); mesh.postion.add(d); How can I ensure that my mesh is facing the direction it's moving in? I ...

Guide to invoking a user-defined server-side function using the MongoDB Node.js driver

After implementing a custom function in system.js to check if a number is odd or not, I encountered an issue where I was unable to call it with the aggregate function of the Node.js driver. How can this function be properly invoked? ...

Please review the photo libraries for any identical URLs

Is there a way to quickly retrieve selected images from the photo library without iterating through all photos, especially when dealing with a limited number of assets? I am currently experiencing slow performance using my current method. The code snippet ...

The Javascript function is being called, yet it cannot be defined

I am currently in the process of revamping an older website that was originally designed for compatibility with IE8 and utilizes framesets for layout management. As part of this update, I am trying to implement a piece of code within one frame that will g ...

Ways to prevent map object issues in the autocorrelation script

Hi there! I came across this autocorrelation script that I'm interested in using: import numpy def acf(series): n = len(series) data = numpy.asarray(series) mean = numpy.mean(data) c0 = numpy.sum((data - mean) ** 2) / float(n) ...

Creating tabs in JavaScript using REST API after div elements have been generated

I found a great resource for creating tabs using JavaScript: The code provided in the link creates tabs based on the number of 'tab-content' divs within the 'tab-container'. In my current project, I am dynamically generating the ' ...

Guide on retrieving the AWS IAM user in string/json format using STS GetCallerIdentity Caller JS/TS

I am attempting to retrieve the AWS IAM Arn user using the STS GetCallerIdentity API provided by Amazon. The following code successfully logs the correct data in the console. Nevertheless, I am encountering difficulty returning the data as a string or JSON ...

Configuring relative file paths within the folders in tsconfig.json

In my project, I have set up a root folder named "TypescriptProgramming" which contains the tsconfig.json file. Inside this root folder, there is another folder called "chapter1" that further includes a folder named "minfunction". The minfunction folder ho ...

Utilizing Node.js to match arrays

let items = ["Product",["car","Bike"]]; let result = items[1].map((item) => [items[0], item]); console.log(result); My current output is: [["Product" , "car"], ["Product" , "bike"]], The above code works for this simple output, but I'm unsure ho ...

Capturing information within a jQuery function by accessing data from another function

Can data be collected from another function while the function is running? // Custom Function function getData(){ var name = 'tom'; return name } // Main Target Area $('.myDiv').click(function(){ // I need to retrieve dat ...