I'm pretty new to Nodejs+Express. I have to connect my Nodejs+Express app to MongoDB which I'm struggling to do. This TypeError: Cannot read property 'forEach' of undefined has been showing up. I'm following this tutorial https://www.youtube.com/watch?v=yH593K9fYvE&feature=youtu.be There's a simple table in my MongoDB database with ids and names which I have created. Appreciate any kind of help! I believe there's an issue in the db.ejb file. But I'm not so sure.
This is my server.js code:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
let port=process.env.PORT || 4000;
const ejs = require('ejs');
app.set('view engine', 'ejs');
//mongoose
mongoose.connect('mongodb+srv://cluster0:83QY2ecAEcLVDeQI@cluster0.srrxv.mongodb.net/newdataDB?retryWrites=true&w=majority');
let dataSchema = new mongoose.Schema({
id: String,
name: String
})
const Data = mongoose.model('Data', dataSchema);
//api routes
app.get('/', (req, res) => {
Data.find({}, function(err, r){
res.render('db', {
results : r
})
})
})
app.listen(port, ()=>{
console.log('Example app is listening on port http://localhost:${port}')}); ```
This is the views/pages/db.ejs code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="container">
<h2>Database Results</h2>
<ul>
<% results.forEach(function(r) { %>
<li><%= r.id %> - <%= r.name %></li>
<% }); %>
</ul>
</div>
</body>
</html>