0

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.

7
  • 1
    Field.find({})? why have you passed empty object to find? as it will not return anything and then you are doing sort on it. Commented Mar 23, 2019 at 17:10
  • as far i know find method will return all the occurrences from Field Commented Mar 23, 2019 at 17:16
  • True - docs.mongodb.com/manual/reference/method/db.collection.find Commented Mar 23, 2019 at 17:20
  • 1
    Can you show us the outcome of console.log(field); right before the res.render? Commented Mar 23, 2019 at 17:24
  • You also need to add an if (err) throw err; Commented Mar 23, 2019 at 17:25

1 Answer 1

1

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>
<% } %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.