The code does run at first but the moment I submit my first post request, it gives the following error :
node:events:504 throw er; // Unhandled 'error' event ^
TypeError: Cannot read properties of null (reading 'name')
Currently using : Node.js, mongoose
Packages used : express, bodyParser, ejs, Mongoose
JS file code :
const express = require("express");
const app = express();
app.use(express.static("public"));
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
const ejs = require("ejs");
app.set("view engine", "ejs");
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/learndb");
const questionSchema =
{
question : String,
answer : String
};
const Question = mongoose.model("Question", questionSchema);
const subjectSchema =
{
name : String,
questions : [questionSchema]
};
const Subject = mongoose.model("Subject", subjectSchema);
app.post("/", function(req, res)
{
const subjectName= req.body.subjectName;
const subject = new Subject({ name: subjectName});
subject.save();
res.redirect("/");
});
app.get("/", function(req, res)
{
Subject.find({}, function(err, foundSubjects)
{
res.render("home", {whichSubjects: foundSubjects});
});
});
HTML/EJS File code:
<body>
<h1>Choose a Subject</h1>
<% whichSubjects.forEach(function(eachSubject) { %>
<div class="">
<form class="" action="/<%=eachSubject.name%>" method="get">
<button type="submit" name="button"> <%=eachSubject.name%></button>
</form>
</div>
<% }) %>
<div class="">
<form class="" action="/" method="post">
<input type="text" name="subjectName" value="">
<button type="submit" name="button">Add A Subject</button>
</form>
</div>
</body>
The answer was so simple but we missed it. The first thing wrong in your code are the paths. You have two paths named /. You want to make your home route the place your visualize all the data and then make a form that posts the data to a different route and upon success, should redirect to your home route. In your case all you have to do is change the post route on the hmtl to /addsubject and on the js file to app.post('/addsubject' rest of code
//Generate express app
const express = require('express');
const app = express();
app.set('views', './views');
app.set('view engine', 'ejs');
//Generate body parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Connect to MongoDB
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/learndb');
const subJectSchema = new mongoose.Schema({
name: String,
questions: [{type: String}]
})
const Subject = mongoose.model('Subject', subJectSchema);
app.post('/addsubject', (req, res) => {
const subjectName = req.body.subjectName;
const subject = new Subject({ name: subjectName });
subject.save((err, subject) => {
if (err) {
console.log(err);
} else {
console.log("User Saved");
}
});
res.redirect('/');
});
app.get('/', (req, res) => {
Subject.find({}, (err, subjects) => {
if (err) {
console.log(err);
} else {
res.render('home', { subjectList: subjects });
}
});
});
app.listen(4000, () => {
console.log('Server started on port 3000');
});
<body>
<h1>Choose Subject</h1>
<div>
<form action="/addsubject" method="post">
<label for="name">Name</label>
<input type="text" name="subjectName" id="name">
<input type="submit" value="Create Subject">
</form>
</div>
<% if(subjectList.length> 0){ %>
<% subjectList.forEach(subject=>{ %>
<p>
<%= subject.name %>
</p>
<% }) %>
<% } else { %>
<p>No subjects found Add Some</p>
<% } %>
</body>