GET request always defaults to /(?:)/i - how can i make it 'undefined'?

73 views Asked by At

If i use RegExp then my Search Widget page always gets: /(?:)/i

And thus always loads with a list of results. I dont want this this to happen. I just want my page to load, then a user fills out the search box and it then does the GET request.

app.get("/la_widget", function(req, res) {

  var test = new RegExp(req.query.search, 'i');
  console.log(test);

  Restaurant.find({
      LocalAuthorityName: test
    },
    null,
    {
      limit: 50
    },
    function(err, foundAuthority) {
      if (foundAuthority) {
        res.render("la_widget", {foundAuthority})
    } else {
      res.render("la_widget", "No local authority matching that input was found.");
    }
  });
});
1

There are 1 answers

6
Matt On BEST ANSWER

Test if the req.query.search string is defined (thuthey) before setting the search query.

const test = (req.query.search) 
  ? new RegExp(req.query.search, 'i')
  : undefined

This uses a ternary operator which equates to:

let test
if (req.query.search) {
   test = new RegExp(req.query.search, 'i')
}
else {
   test = undefined
}