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
addPlayer
function
- Make sure to add a comma after the
- Set the value of
getPlayersList
to a newasync
function with no parameters - In the body of the function, create a new variable named
playerKeys
- Use
db.list
to get all keys prefixed with"player"
- This will retrieve all the player objects inserted into the database
- Add an
await
beforedb.list
so 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
for
loop structure looping throughplayerKeys
- In the body of the
for
loop, 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 thecurrentPlayer
object tocurrentKey
- This will come in handy later
push
thecurrentPlayer
object to theplayers
list- Outside of the
for
loop, return theplayers
list
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,
require
the db.js module withrequire('../db')
- Store the value in a
const db
- Store the value in a
- Add an
async
keyword in front of thegetHomePage
function to make it async - In the body of the
getHomePage
function, above theresponse.render
, create a new variable namedresult
- Set the
result
variable to anawait
ed call to thedb.getPlayersList
function - Under that, create a new variable named
renderData
, set to an empty object - Add a
players
property to therenderData
object, set toresult
- In the
response.render
call, pass in therenderData
object
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!