CRUD App - Read
Follow the steps below to allow the web app to display existing data from the database.
Getting the Data from the Database
First, define a function to get all the player data from the database.
- In the db.js file, add a new module export property named
getPlayersList- Make sure to add a comma after the
addPlayerfunction
- Make sure to add a comma after the
- Set the value of
getPlayersListto a newasyncfunction with no parameters - In the body of the function, create a new variable named
playerKeys - Use
db.listto get all keys prefixed with"player"- This will retrieve all the player objects inserted into the database
- Add an
awaitbeforedb.listso that the code does not continue until the keys are retrieved - Under that, create a new empty list variable named
players- This will store the nicely formed video objects
- Create a
forloop structure looping throughplayerKeys - In the body of the
forloop, get the current key ascurrentKey - Retrieve the value for the current key using
await db.get- Store that in a variable named
currentPlayer
- Store that in a variable named
- Set the
"id"property of thecurrentPlayerobject tocurrentKey- This will come in handy later
pushthecurrentPlayerobject to theplayerslist- Outside of the
forloop, return theplayerslist
Code
getPlayersList: async function() {
let playerKeys = await db.list("player_");
let players = [];
for (let i = 0; i < playerKeys.length; i++) {
let currentKey = playerKeys[i];
let currentPlayer = await db.get(currentKey);
currentPlayer["id"] = currentKey;
players.push(currentPlayer);
}
return players;
}
Passing the Data to the Page
Now that there is a way to get the data from the DB, it's time to show it on the homepage.
Back-end Updates
Update the routes/index.js file to pass the data when rendering.
- At the top the index.js file,
requirethe db.js module withrequire('../db')- Store the value in a
const db
- Store the value in a
- Add an
asynckeyword in front of thegetHomePagefunction to make it async - In the body of the
getHomePagefunction, above theresponse.render, create a new variable namedresult - Set the
resultvariable to anawaited call to thedb.getPlayersListfunction - Under that, create a new variable named
renderData, set to an empty object - Add a
playersproperty to therenderDataobject, set toresult - In the
response.rendercall, pass in therenderDataobject
Now the index.ejs file will be able to access the players data!
Front-end Updates
For now, the front-end will just show all the data as a JSON string.
- Open the index.ejs file for editing
- Add code to display the data from
players<%= JSON.stringify(players) %>
Run the program, and verify that it is possible to view the data from the database! It may not look pretty, but it should be there. Try adding another player and make sure they appear in the data too!