W02 Learning Activity: Displaying Database results in EJS
Overview
In previous activities, you have created a database, connected to it from your Node.js application, and created tables with sample data. In this activity, you will learn how to query the database from your Node.js application and render it using an EJS template.
Activity Instructions
Follow these steps to complete the activity:
Create a model file for Organizations
- Create a new file
src/models/organizations.js. - Add a function to query the database and get all the organizations, by adding the following code to the
src/models/organizations.jsfile.import db from './db.js' const getAllOrganizations = async() => { const query = ` SELECT organization_id, name, description, contact_email, logo_filename FROM public.organization; `; const result = await db.query(query); return result.rows; } export {getAllOrganizations}This code does the following:
- Imports the database connection from the
db.jsfile. - Defines an asynchronous function
getAllOrganizationsthat queries the database for all organizations. - Returns the rows of the result if successful.
- Exports the
getAllOrganizationsfunction so it can be used in other parts of the application.
- Imports the database connection from the
Avoid Using SELECT *
Notice that this SELECT statement explicitly lists the column names, rather than using SELECT *. If you use SELECT * you may retrieve unnecessary data, which can impact performance and security. For example, in the future additional columns may be added to the table that you do not want to expose in your application. For this reason, it is a good practice to explicitly specify the columns you need.
Note on Models
In a future lesson you will learn more about the Model-View-Controller pattern and how models help to organize your project.
The important thing to know right now is that all code that works with organizations and getting them from the database should be in the organizations.js file. Then, you will also create other files in the models directory for the other entities in your database.
Use the model function in server.js
- In
src/server.js, import thegetAllOrganizationsfunction, aft the other imports at the top of the file:import { getAllOrganizations } from './src/models/organizations.js'; - Next, use the
getAllOrganizationsfunction to get the list of organizations.- Find the event handler for the organizations route.
- Make sure the event handler is asynchronous, by ensuring the
asynckeyword is present before the function parameters. - Inside the event handler, call the
getAllOrganizationsfunction using theawaitkeyword and store the result in a variable namedorganizations. - For now, add a
console.logstatement to print theorganizationsvariable to the console.
The route handler should now look as follows:
app.get('/organizations', async (req, res) => { const organizations = await getAllOrganizations(); console.log(organizations); const title = 'Our Partner Organizations'; res.render('organizations', { title }); });
Test the query
- Start your Node.js application by running
npm run devin your terminal. - Open a web browser and navigate to
http://127.0.0.1:3000/organizationsto trigger the event handler. - Check the terminal where your Node.js application is running. You should see the list of organizations printed to the console.
- If you see the list of organizations, congratulations! You have successfully queried the database from your Node.js application.
Stop here if you have problems
If you are unable to get the list of organizations printed to the console, you should stop here and get it working before proceeding.
Update server.js to pass the organizations to the EJS template
Now that you have tested the query and verified that you can get the information from the database and display it to the console, you can update your server.js file so that instead of displaying it to the console, you can pass the data to your EJS template to render it.
In the event handler for the organizations route in src/server.js, remove the line of code that displayed it to the console. Instead, pass it to the EJS template by updating the res.render call.
The route handler should now look as follows:
app.get('/organizations', async (req, res) => {
const organizations = await getAllOrganizations();
const title = 'Our Partner Organizations';
res.render('organizations', { title, organizations });
});
Notice that you are passing the organizations list to the template so it has access to it.
Display the results in EJS
Now it is time to display the results in your EJS template.
- Open the EJS template file for the organizations page. This file should be named
src/views/organizations.ejs - In the EJS template file, use a loop to iterate through the
organizationsvariable and display the organization names and contact emails. - Make sure to display all the appropriate information for the organization. You will need to update the image src location to insert the logo file from the database.
EJS Code Example (click to expand)
Your EJS file should look something like the following.
<%- include('partials/header') %>
<main>
<h1><%= title %></h1>
<p>Here are a few of our partner organizations:</p>
<ul>
<% organizations.forEach(organization => { %>
<li><img src="/images/<%= organization.logo_filename %>" alt="<%= organization.name %> logo"><strong><%= organization.name %></strong>: <%= organization.contact_email %></li>
<% }); %>
</ul>
</main>
<%- include('partials/footer') %>
Test the EJS rendering
First test the EJS rendering in your development environment.
- Start your Node.js application by running
npm run devin your terminal (if it is not already running). - Open a web browser and navigate to
http://127.0.0.1:3000/organizationsto view the organizations page. - You should see the list of organizations displayed on the page, including their names, descriptions, contact emails, and logos.
Deploy and test
Finally, deploy your updated code to Render.com and test it in the deployed environment.
- Push your changes to GitHub.
- Render.com should automatically deploy your updated code.
- Once the deployment is complete, open a web browser and navigate to your organizations page at the deployed, render site.
- You should see the list of organizations displayed on the page, just like in your development environment.
Optional Video Walkthrough
While the following video may be helpful to see the steps in action, make sure to walk through the written instructions directly because there may be important steps that are not covered in the video.
Direct link: Displaying Database Results in EJS
Submission
Congratulations! You have now completed all of the learning activities for this week.
To submit this activity, return to Canvas and submit the associated quiz there.
Other Links:
- Return to: Week Overview | Course Home