Leveraging variables within a Regex query in MongoDB using JavaScript

I am trying to locate a specific row in MongoDB using OR and I need to include a JavaScript variable inside the regex. However, when I do this, the query returns null. By replacing /${oriFilename}/ with my file name like "CB0123456781_20210604165222", the query works as expected.

Can someone please guide me on how to correctly insert the JavaScript variable inside the regex?

let oriFilename = files[file]['name'].replace(".txt", "") //returns CB0123456781_20210604165222

 const queryExisted = {
       project_id: ObjectId(project._id),
       test_station: fields.station,
       serial_number: serialNumber,
       mac_address: macAddress,
       $or: [
         { data_txt_filename: { $regex: /${oriFilename}/, $options: 'i' } },
         { log_txt_filename: { $regex: /${oriFilename}/, $options: 'i' } },
         { comport_txt_filename: { $regex: /${oriFilename}/, $options: 'i' } },
         { telnet_txt_filename: { $regex: /${oriFilename}/, $options: 'i' } },
       ]
 }
               
 let existedData = await db.collection("ate_tests").findOne(queryExisted)
                        

Answer №1

Just figured out the solution! It's actually quite simple. If you've already used the $regex option, you don't need to include a backslash before the string you want to search for. In my case, it looks like this:

{ data_txt_filename: { $regex: ${oriFilename}, $options: 'i' } },

I found this helpful answer in a post at

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

` `Showing the Div Content with Php` `

I am trying to create a process where two PHP pages work together. On the first.php page, the user selects orders and a div is filled with this content without any issue. There is also a confirm button that should open the second.php page and display the c ...

The use of a MongoId object as an array is not allowed

I am struggling with displaying the values inside a 2D array using echo. It works perfectly fine with print_r: print_r($array); The output is as follows: Array ( [0] => MongoId Object ( [$id] => 57a789b7ce2350b40e000029 ) [1] => MongoId Object ...

Watching a VideoJS video does not pause even after closing a Bootstrap modal

I am struggling with a modal on my website that contains a video. Even when I close the modal by clicking outside of it or using the close button, the video continues to play in the background. I have tried all the solutions I could find on stackoverflow ...

trigger the focusout event within the focusin event

I am attempting to trigger the focusout event within the focusin event because I need to access the previous value from the focusin event, but the focusout event is being triggered multiple times. $('tr #edituser').focusin(function(){ var ...

Utilize jQuery to retrieve the classes of list elements

I have been using $('#ul li').get() to retrieve all the list elements and store them in an array. Each of these list elements contains specific classes... var i; var listClass = ('#ul li').get(); for(i=0;i<listClass.length;i++){ ...

Set the style of the mat-select element

I'm having an issue with my select option in Angular Material. The options look fine, but when I select one, the strong tag disappears. Can anyone help me style only that part? Thank you in advance. <mat-select formControlName="projectId" ...

terminate a node-cron task or abort a node-scheduler job

I'm currently working on a nodejs project that involves managing multiple cron jobs. However, I've encountered an issue when attempting to cancel these jobs. Here's the scenario: I have set up several cron jobs using node-cron or node-sch ...

modifying Redux state according to the position in an array

In my food truck app, I have stored customer orders in the redux state as an array of objects. Each order includes a list of items selected by the customer, along with the count, name, and total price for each item. For example: state.order = [ {item: " ...

Executing grunt on the necessary dependencies

I am working on 3 different projects that all utilize grunt for automation tasks. Project a has dependencies on project c and b Project b depends on project c Project c does not have any dependencies Both Project a and b require a step to compile pro ...

Tips for displaying Facebook comments with JavaScript

Can anyone help me figure out how to customize the data-href for Facebook comments using JavaScript (jQuery)? I tried incorporating the code below, but it's not displaying anything in the div col2. $("#col2").html( id+"<div class='fb-comm ...

The XMLHttpRequest's readystate gets stuck at 1 stage

Feeling a bit out of practice here - used to work with AJAX directly, but then spent a few years on a jQuery site and now my native JS skills are rusty. I've simplified my code as much as possible, but it's still not functioning: var rawfile = ...

Trouble with initializing the Ionic map controller

I have a mobile app with 5 tabs, one of which features a map. However, the map only loads when directly accessed through the URL bar. It seems that the controller is not loaded when navigating to the map tab through the app, as indicated by console logs. S ...

What is the best way to display comprehensive data labels with highcharts?

I am facing an issue with displaying the variable targets for the data labels in the chart below. The series data labels are only showing the value of targetsAdj. I attempted to add stacked labels on the y-axis but it did not have the desired effect. Is th ...

The GridFS/multer module is encountering an issue where it is unable to access the 'filename' property of an undefined

My knowledge in web development is limited, so forgive me if this question seems naive. The issue I am facing involves Node.Js and the creation of a database to store and display images on a browser using an .ejs file. While I can successfully log the im ...

Error 56 EROFS encountered when trying to save a file in Node.js filesystem every 2 seconds

I've set up a node.js environment on my raspbian system and I'm attempting to save/update a file every 2/3 seconds using the code below: var saveFileSaving = false; function loop() { mainLoop = setTimeout(function() { // update data ...

Utilize AJAX to fetch and display the response from a Node JS route directly onto an HTML page

At the moment, I am retrieving client-side HTML/JS inputs (var1 and var2) which are then sent to server-side Node JS. The input values are stored in variables through an AJAX post call made to a specific route. What I want now is to define the values of v ...

Next.js version 10.0.5 presents an issue with undefined environment variables

I recently started building a website using Next.js and encountered an issue while trying to integrate Google Tag Manager. Despite following the tutorial provided in the Next.js Github example, I found myself unable to access my environment variables. ...

Supplying information to my ejs template while redirecting

I am currently working on a feature that involves sending data from the login page to the home page when the user is redirected. This data will then be used in the home EJS file. Below is the code snippet I have implemented: module.exports = functio ...

Error encountered when serving tiles using Node JS and Leaflet from the same domain

I have been utilizing the script found at: to run my web application that overlays tile layers from: However, for the past two days, I have been experiencing an issue where tiles are being called in places where they were not previously, causing slow til ...

Is there a way to establish a relationship between a model and the User model using Express/Mongoose?

I am currently working with two models: the User model and the Course model. My goal is to create a system where when a User (Teacher) creates a course, it automatically assigns that course to them and vice versa. To better illustrate this concept, here ar ...