0

I want to find the existing row in the MongoDB using OR and I need to put JavaScript variable inside the regex, but it make the query returns null. I've tried to replace the /${oriFilename}/ with my file name e.g. "CB0123456781_20210604165222", and it works.

How to put the JavaScript variable correctly 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)
                        
richardoey
  • 25
  • 4

1 Answers1

0

I just currently got the answer. Really simple, if you have already used $regex option, you don't have to put \ before the string you want to search. So in my case, it would be

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

Got the answer from this post https://stackoverflow.com/a/12770931/7936827

richardoey
  • 25
  • 4