Display MongoDB Data on UI using Node.js and EJS
Make GET request call
app.get("/", async (req, resp) => {
await client.connect();
const db = client.db(dbName);
const collection = db.collection("students");
const result = await collection.find().toArray();
console.log(result);
resp.send("Data will be here");
});
Make EJS template file
Create a file named students.ejs
inside the views
folder.
<table>
<tr>
<td>Name</td>
<td>Age</td>
<td>Email</td>
</tr>
<% students.forEach(student => { %>
<tr>
<td><%= student.name %></td>
<td><%= student.age %></td>
<td><%= student.email %></td>
</tr>
<% }) %>
</table>
Make GET request call
app.get("/", async (req, resp) => {
await client.connect();
const db = client.db(dbName);
const collection = db.collection("students");
const result = await collection.find().toArray();
console.log(result);
resp.send("Data will be here");
});
Set view engine
app.set("view engine", "ejs");
Render students.ejs
file
resp.render("students", { students: result });