Home > Mobile >  How to render multiple data on Ejs template file from MongoDB database
How to render multiple data on Ejs template file from MongoDB database

Time:08-07

Please look at the code and solve this problem

enter image description here

In the Image only One data is rendering at a time but I want to render more than one data from the database. In the mongo database there are three entries but when I take the data from the database only one data is rendering.

Below is the code I used to render data from the database

enter image description here

enter image description here

CodePudding user response:

You need to pass the array itself to the template instead of calling res.render for each entry:

const contacts = results.map(contact => ({
    Fname: contact.fname,
    Lname: contact.lname,
    Email: contact.email,
    Phone: contact.phoneNumber
}));

res.render("saved", {
    contacts
});

Then in your template use forEach to iterate the data and render each entry, e.g.:

<ul>
 <% contacts.forEach(function(contact) { %>
    <li> First Name:<%= contact.Fname %> Last Name:<%= contact.Lname%></li>
 <% }); %> 
</ul>
  • Related