Zahid Hasan
Zahid Hasan

Reputation: 1

can't fetch data from mongodb and display that into html

model named Field.js

    const mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost:27017/SuperchainV1', { 
    useNewUrlParser: true });
    mongoose.set('useNewUrlParser', true);
    mongoose.set('useFindAndModify', false);
    mongoose.set('useCreateIndex', true);
    const db = mongoose.connection;
    const FieldSchema = mongoose.Schema({

    productID: {
    type: String
    },
    productName:{
    type: String
    },
    fieldLocation: {
    type: String
    },
    farmerName: {
    type: String
    },
    farmerMobile: {
    type: String
    },
    farmerNid: {
    type: String
    },
    date: {
    type: Date,
    default: Date.now
    }
    });


    const Field = mongoose.model('Field', FieldSchema);
    module.exports = Field;

routes index.js

   router.get('/dashboard', ensureAuthenticated, (req, res) => {
   let field = Field.find({})
   .sort({date:'desc'}).exec( (err, field) => {
    res.render('dashboard', field);
        });
     })

dashboard.ejs where i want to display data after fetching

    <div class="jumbotron">
       <p class="lead">
         <% field.productID %>
         <% field.productName %>
         <% field.fieldLocation %>
         <% field.farmerName %>
         <% field.farmerNumber %>
         <% field.farmerNid %>
        </p>
    </div>

errors i get "field is not defined"

I want to fetch data from collections fields and display all the data into a ejs page named dashboard i tried this but always get the error field is not defined.

Upvotes: 0

Views: 75

Answers (1)

Manzurul Hoque Rumi
Manzurul Hoque Rumi

Reputation: 3104

You need to use for loop in ejs template

<% for(var i=0; i < field.length; i++) { %>
   <div class="jumbotron">
       <p class="lead">
         <%= field[i].productID %>
         <%= field[i].productName %>
         <%= field[i].fieldLocation %>
         <%= field[i].farmerName %>
         <%= field[i].farmerNumber %>
         <%= field[i].farmerNid %>
        </p>
    </div>
<% } %>

Upvotes: 1

Related Questions