简体   繁体   中英

Print data from mongodb to ejs using nodeJS

I have this kind of JSON data. This data is fetched from MongoDB. I want to print that on EJS page.

[ { _id: 59157619e9bcd218d9dd4dba, que: 'Overall how satisfied are you with the product?', type: 'radio', options: [ 'Not at all satisfied', 'satisfied', 'Very much satisfied ' ] } ]

options would be radio button.

suppose you have get api like this.

app.get('/testing', function (req, res) {
    var array = [{
        _id: '59157619e9bcd218d9dd4dba',
        que: 'Overall how satisfied are you with the product?',
        type: 'radio',
        options: ['Not at all satisfied', 'satisfied', 'Very much satisfied ']
    }]
    res.render('load', array);
    //load is the ejs file (load.ejs) and array is the array of object.
});

Suppose this is your ejs file and you want to send this array in ejs file.like...

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
    table, td, th {
     padding: 8px;
    border: 1px solid #ddd;
    text-align: left;
}
</style>
</head>
<body>
    <h2><%= HeadLine %></h2>
    <table>
        <tr style='background-color: gainsboro;'>
            <th>Id</th>
            <th>question</th>
            <th>type</th>
            <th>options</th>
        </tr>
        <% array.forEach(function(data) { %>
        <tr>
            <td >

     <p><%= data.seq %></p>    

            </td >
            <td>
                <p><%= data.id %></p>
                </td>
             <td >
            <p>  <%= data.question %></p>
            </td >
            <td >
            <p><%= data.type %></p>
            </td >
            <td >
        <p> <%= data.options %></p> 
            </td >                       
        </tr>
<% }); %>
    </table>
</body>
</html>

You need to pass the json data to the ejs file from the router file, this might help- router.js

router.get('/radio', function(req, res) {
    var data = [ { _id: 59157619e9bcd218d9dd4dba, que: 'Overall how satisfied are you with the product?', type: 'radio', options: [ 'Not at all satisfied', 'satisfied', 'Very much satisfied ' ] } ]; //replace this with the service getting data
    res.render('radio/show', data);
})

ejs file - radio.js

<form>
  <input type="radio" checked><%= data.options[0] %><br>
  <input type="radio"><%= data.options[1] %><br>
  <input type="radio"><%= data.options[2] %><br>  
</form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM