Adding a Search

Menu
Menu

Adding a Search

Searching the Data

The head.ejs partial included the HTML for a search form:

src/views/partial/head.ts

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:

src/controller/controller.ts

The controller function getDataByTitle is used to search a MongoDB database for films based on a given filmTitle. Let's break down the function:

Don't forget to add getDataByTitle to the exported functions.

Add a Route

With the controller in place add a route of:

src/routes/routes.ts

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