node.jsformsexpressgetxregexp

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


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.");
    }
  });
});

Solution

  • 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
    }