0

I'm building a dynamic search query for a Mongo database.

In short, and not directly related to the question... it looks like this:

var searchCriteria = {}; <-- start with empty object    

return db.users.find(searchCriteria,
    { sort: { username: 1 }
});

The values for searchCriteria come from a search form, basically like this:

var filter = $(form).find('select[name=filter]').val();
var query = $(form).find('[name=query]').val();

searchCriteria[filter] = query <-- Using a dynamic key

Example output from the form:

console.log(searchCriteria);
>> { username: "jdoe" }

So here's my hangup. I need to "unstringify" the query within the searchCriteria, and turn it into this:

>> { username: /jdoe/ }

I've tried replace, among other things, but it keeps ending up as a string value. I need the /query/ in that format for the Mongo find query.

Any suggestions? Thank you :)

7
  • 7
    Huh? Are you trying to turn a string into a Regex? If so, just new RegExp(string); Commented Oct 7, 2014 at 18:08
  • 1
    Just FYI {} is an empty object, not an empty array. Commented Oct 7, 2014 at 18:09
  • 1
    var searchCriteria = {}; is not an array, its an object Commented Oct 7, 2014 at 18:09
  • is there a reason why you need this ? may there is a option for other possibilitys to solve this if we know what you want to do with it :) Commented Oct 7, 2014 at 18:11
  • @ZekeSonxx I can't believe I missed this... How embarrassing. Please post as answer and I'll accept. Commented Oct 7, 2014 at 18:11

1 Answer 1

1

You can easily turn a string into a RegExp object by using new Regex(string).

Note that this is bound to have some security issues somewhere if you're passing in user input, but new RegExp shouldn't allow any arbitrary JS to run, but it could still crash your code by being an invalid Regex.

Source (MDN)

Sign up to request clarification or add additional context in comments.

3 Comments

someone should probably mention something about escaping special chars and sanitizing user input.
@dandavis Good call. In my case, it's a protected admin page on a site.
@dandavis Hah. Me either :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.