0

I'm trying to load and display several work entries from my MongoDB database using mongoose and Express and I'm running into trouble.

When I try to pass the results to my .ejs file, I get the error that the variable is not defined.

For some reason, it works when I pass individual objects to the .ejs file.

Here's what is working, but isn't useful

router.get('loadEntries', (req,res) => {
  Entry.find({}, function(err, data) {
    data.forEach(function(item) {
      res.render('loadEntries',{firstName:item.firstName});
    }
  });
});

//ejs file. Very basic, just to capture the data
<p>
    <%=firstName%>
</p>

Here's what I would like to do, but isn't working

router.get('loadEntries', (req,res) => {
  Entry.find({}, function(err, data) {
      res.render('loadEntries',{result:data});
    });
});

//ejs file
<p>
  <%result.forEach(function(item) { %>
    First name: <%=item.firstName%>
    Last name: <%=item.lastName%>
  <%})%>
</p>

My mongoose model

const mongoose = require('mongoose');

const EntrySchema = new mongoose.Schema({
  //hours, room, buliding, note
  hours: {
    type: Number,
    required: true
  },
  room: {
    type: String,
    required: true
  },
  building: {
    type: String,
    required: true
  },
  note: {
    type: String,
    required: false
  },
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  }
});

const Entry = mongoose.model('Entry', EntrySchema);

module.exports = Entry;
  • can you post your mongoose model? – dimitris tseggenes Mar 05 '19 at 20:29
  • @dimitristseggenes Okay, I have added my mongoose model. Though, I am able to save new entries without issue –  Mar 05 '19 at 20:38
  • It looks good. I don't know why it does not work. Maybe there is a problem with `forEach` loop. Try to use `for .. of` loop like this `<% for (let item of result) { %>` – dimitris tseggenes Mar 05 '19 at 21:09
  • @dimitristseggenes yeah, it still tells be it is undefined. I'm stumped. Whenever I try to load something from the database and display it with this method I run into this issue –  Mar 05 '19 at 21:42
  • what is the result of a `console.log(data);` before `res.render`? – Lord Elrond Mar 06 '19 at 06:31
  • If you want to mapping of data and send it to your veiw you can check this it will help you for your result [data mapping https://stackoverflow.com/questions/14103615/mongoose-get-full-list-of-users] – Muhammad Shareyar Mar 08 '19 at 17:33
  • Just an update, this was resolved. The issue was simply that I included everything in the "GET" method code for the ejs file of loadEntries. Well, load entries wasn't being fetched with GET. Instead, I was "include"ing it in another view. So I had to pass the value to the primary view instead. –  Mar 23 '19 at 01:06

0 Answers0