Mongoose query using conditional formatting and regex
First, using new RegExp on user input is a bit like running eval on user input (though not nearly as bad - usually). If it can be avoided, it should be. In this case, if I pass .*? as the partName, the regex will be /^.*?$/i which will match every entry in the database, or I could pass ( which would result in the function throwing an error. This can be mitigated by escaping all special characters, but still isn't a good idea if there is another way to do this. (I haven't used MongoDB, but it appears the $search key might be useful - MongoDB Docs.



If the built in $search parameter doesn't work for you, then the function should escape all special characters in the search string before creating a RegExp with it.

One way to do this is the following:



function createRegex(userInput) {
  return new RegExp(
    // Escape all special characters except *
    "^" + userInput.replace(/([.+?^=!:${}()|\[\]\/\\])/g, "\\$1")
      // Allow the use of * as a wildcard like % in SQL.
      .replace(/\*/g, ".*") + "$",
    'i'
  );
}

['test', '*test*', '*test', 'test*', '[tes{2}t.'].forEach(test =&gt; {
  console.log(test, '=&gt;', createRegex(test))
});




While this may be slightly slower than the current function, it is much safer and can greatly simplify the createQuery function. It also allows createQuery to cover the edge case where * appears in the middle of a string.

createQuery can now be implemented in only a few lines. 

function createQuery(userInput, dbField) {
  if (userInput === undefined) {
    return;
  }
  // Trim the input before checking as otherwise searching for a
  // single space could cause problems.
  userInput = userInput.trim();
  if (userInput !== "") {
    query[dbField] = createRegex(userInput);
  }
}


Alternatively, this could be shortened (at the cost of some readability) with 

function createQuery(userInput, dbField) {
  if (userInput &amp;&amp; userInput = userInput.trim()) {
    query[dbField] = createRegex(userInput);
  }
}