Adding a Search
Searching the Data
The head.ejs partial included the HTML for a search form:
The form makes a GET call to films and will pass a querystring parameter of filmTitle.
If the user searches for 'star', this call will take the form of localhost:3000/films/search?filmTitle=star
In this example we will use the same src/views/films view as this is already set up to recieve an array of results.
Add a new Controller
We need to query our model based on the user query. To do so add a controller of:
The controller function getDataByTitle is used to search a MongoDB database for films based on a given filmTitle. Let's break down the function:
The function is declared as
async, indicating that it will return a Promise. The returned Promise will resolve to an array ofIFilmobjects representing the films matching the search criteria or an object containing an error message if an error occurs during the process.The
filmTitleparameter is a string that represents the title to search for.Within the function, a
try...catchblock is used to handle any potential errors that may occur during the execution of the code.Inside the
tryblock, a case-insensitive regular expression is created using theRegExpconstructor. TheRegExpconstructor takes two parameters: the first is the string to search for (filmTitlein this case), and the second is a string representing the regular expression options. The "i" option is passed to create a case-insensitive search.The regular expression
regexis then used in the MongoDB query to search for films. TheFilm.find()method is called with a query object specifying thefilmTitlefield to match against theregex.The
awaitkeyword is used beforeFilm.find()to wait for the database query to complete and fetch the results. The results are assigned to thefilmsvariable.Finally, the
filmsarray is returned from the function if the query is successful, containing the films that match the search criteria.If any error occurs during the execution of the code, it will be caught in the
catchblock. An error message will be logged to the console usingconsole.error(), and an object with anerrorproperty containing a descriptive error message will be returned.
Don't forget to add getDataByTitle to the exported functions.
Add a Route
With the controller in place add a route of:
In the above the query string allows clients to pass additional parameters or data to the server as part of the GET request URL ie /films/search?filmTitle=star.
Inside the route handler, req.query is an object that contains the query string parameters from the URL. In this case, req.query.filmTitle retrieves the value of the "filmTitle" query parameter passed in the URL.
The filmTitle is then sent to the controller function getDataByTitle().
As the data returned is similar in structure to the earlier example that retrieved all films, then we can re-use the films EJS template called by the res.render.
We now have a search feature.
Next: CRUDing Web Views