0

Trying to query the database with this code: I have a string within 'nameInput' that I want to find documents that contain it.

var arg = {"$and":[{"name":{'$regex' : nameInput, '$options' : 'i'}}, {"thing": selectedThing}]}

I plug in arg into the find() method and it returns this error: errors.js:20 Uncaught (in promise) Error: $regex requires regular expression

Any idea how this can be fixed? I've tried replacing nameInput by using the RegExp method in Javascript to no avail. (e.g new RegExp(nameInput, 'i'))

yasgari
  • 21
  • 3

1 Answers1

0

If you’re trying to find a string within nameInput then you need to make that the field you do the regex on. Try this:

nameInput : { $regex : /pattern-you-want-to-find/, $options : ‘i’ } }

Apologies for the brief answer, but if provide a more detailed question and an example document I can try and help a little more.

  • Thanks for the answer! the problem is that I can't hard code it in.. im getting the nameInput variable's value from a text field on a webpage, which Im then passing in to do a contains query through pymongodb – yasgari Feb 05 '18 at 01:22
  • @yasgari Can't hard code what in? `nameInput` is a `key` and the `value` is the variable you've pulled from a text file and then matched on...... So when you come to do your `$regex` `nameInput` would be classed as the `field` to which you then want to run your regex on the value within. –  Feb 05 '18 at 08:22
  • Let me elaborate further- I have a website with an html page containing several text fields for searching. The variable `nameInput` is set in the event handler for the form containing those textfields; its set to the value of the field users type in a name to search. like so: `nameInput = document.getElementById('gene').value;` So now since this variable contains the string I want to find, I want the DB to query and find any documents (in column `name`) containing the string passed in, stored in `nameInput` Hope this helps! Apologies as this is my first post on here – yasgari Feb 05 '18 at 16:22
  • The answer in this OP might help: https://stackoverflow.com/questions/13224753/mongodb-pymongo-how-to-escape-parameters-in-regex-search –  Feb 05 '18 at 17:43