Build a Basic M.E.N. Site - 3 - Database to Front-end
The server is up and running, the database is set and ready to collect information from the user.
Next we want to READ data from our database and show them to the user.
READ data from MongoDB
We want to GET data from the server/database, so the request will be pout under the
.get()
method.
In MongoDB we can use.find()
method to find documents inside a colletion.
This.find()
method will return a cursor (a Mongo object) whitch contains informations of the documents that we want to find.
(try to console.log this cursor object?!)app.get("/", function(req, res){
var cursor = db.collection("plusorminus").find();
})Use
.toArray()
method for this cursor object to put the informations inside an array.
The.toArray()
method takes in a callback function. We can tryconsole.log()
the results.cursor.toArray(function(err, results){
console.log(results)
})Put in the actions that I want to do.
Count the choice of all user andconsole.log()
out the counts.
The.get()
section of code will now look like this:app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html")
var cursor = db.collection("plusorminus").find()
cursor.toArray(function(err, results){
if (err) return console.log(err)
var plus = 0
var minus = 0
for (i = 0; i < results.length; i++){
if (results[i].plusorminus == "+"){
plus += 1
}
else {
minus += 1
}
}
console.log("plus: " + plus)
console.log("minus: " + minus)
})
})
Show data to users using EJS
We now have the data retrived from MongoDB and console.log()
in the console. We should use a template engine to serve it to a HTML file.
Install EJS and Edit The Server
Install EJS
npm install ejs --save
set the
view engine
toejs
in NodeJS/Express server by adding a line inside theserver.js
file.app.set("view engine", "ejs")
Render the page with template.
The rendering is done by the.render()
method underresponse
, the syntax is:res.render(VIEW, DATA)
The VIEW is the file that we want to render (like XXX.ejs) and the DATA will be an object that passes data into the VIEW.
I want to latter render anindex.ejs
file and send the results to the web page. So I will add this line inside theapp.get()
section, and comment out the originalres.sendFile()
method:res.render("index.ejs", {
results: results
})
Edit EJS File
Create the
views/
folder and the EJS file.
EJS will search automatically inside theviews/
folder for files that we want to render. So we can create aviews/
folder and anindex.ejs
file inside.mkdir views
touch views/index.ejsInside the EJS file
An EJS file is actually an HTML file in whitch we can write JavaScript code. So we can copy the content inside theindex.html
file and add the EJS part inside. The wholeindex.ejs
file will look like this:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MY APP</title>
<link rel="stylesheet" type="text/css" href="/style.css">
</head>
<body>
<img src="/ covid19.svg">
<form action="/plusorminus" method="POST">
<input name="FacebookName" type="text" placeholder="Your Name">
<span> prophesy:</span>
<br>
<label value="21032020">New cases on 06/04/2020 will be</label>
<br>
<input name="date" type="hidden" value="21032020">
<button class="plusbutton" type="submit" name="plusorminus" value="+">More</button>
<span>/</span>
<button class="minusbutton" type="submit" name="plusorminus" value="-">Less</button>
<br>
<span>then the new cases on 05/04/2020</span>
</form>
<hr>
<h2>True Prophet?
<br>False Prophet?</h2>
<div class="plus">
<h3> More</h3>
<ul>
<!-- EJS part -->
<% for(var i = 0; i < results.length; i++){ %>
<% if (results[i].plusorminus == "+") { %>
<li class="user"><%= results[i].FacebookName %></span>
<% } %>
<% } %>
<!-- end of EJS part -->
</ul>
</div>
<div class="minus">
<h3> Less</h3>
<ul>
<!-- EJS part -->
<% for(var i = 0; i < results.length; i++){ %>
<% if (results[i].plusorminus == "-") { %>
<li class="user"><%= results[i].FacebookName %></span>
<% } %>
<% } %>
<!-- end of EJS part -->
</ul>
</div>
</body>
EJS’ syntax is quite simple. Use <% %>
to write JavaScript inside. And <%= %>
can output JavaScript’s result as string.
BTW, one little thing to be careful. The } else {
statment should be put in the same <% %>
tag. There will be an error if you separate }
and else {
to two lines. Examples:
// correct |
Now we have a working server connect to a database. We are able to POST data to the server/databse and GET data from the server/database (both in a very basic stage ofcourse). But this page looks MXXXX FXXXXX ugly. Some styling will then be needed.