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;